-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1997 lines (1707 loc) · 73 KB
/
app.py
File metadata and controls
1997 lines (1707 loc) · 73 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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import re
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import streamlit as st
try:
import pdfplumber
except Exception:
pdfplumber = None
try:
from docx import Document
except Exception:
Document = None
try:
import jinja2
except Exception:
jinja2 = None
try:
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
except Exception:
A4 = None
getSampleStyleSheet = None
ParagraphStyle = None
cm = None
SimpleDocTemplate = None
Paragraph = None
Spacer = None
PageBreak = None
# =============================
# APP CONFIG
# =============================
st.set_page_config(page_title="CV Tailor Studio", layout="wide")
OUTPUT_DIR = Path("output_cv_studio")
OUTPUT_DIR.mkdir(exist_ok=True)
DEFAULT_HTML_TEMPLATE = r"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Tailored Application</title>
<style>
body { font-family: Arial, sans-serif; background:#f5f7fb; color:#1f2937; margin:0; }
.page { max-width:900px; margin:24px auto; background:#fff; padding:32px 40px; border-radius:16px; box-shadow:0 8px 24px rgba(0,0,0,0.08); }
h1,h2,h3 { margin-bottom:8px; }
h2 { border-bottom:2px solid #e5e7eb; padding-bottom:6px; margin-top:24px; }
.meta { color:#4b5563; margin-bottom:16px; }
ul { padding-left:20px; }
.entry { margin-bottom:14px; }
.entryhead { display:flex; justify-content:space-between; gap:12px; flex-wrap:wrap; font-weight:700; }
.small { color:#4b5563; }
</style>
</head>
<body>
<div class="page">
<h1>{{ cv.header.name }}</h1>
<div class="meta">
{{ cv.header.email }}{% if cv.header.phone %} | {{ cv.header.phone }}{% endif %}{% if cv.header.location %} | {{ cv.header.location }}{% endif %}
</div>
{% if cv.summary %}<h2>{{ labels.profile }}</h2><div>{{ cv.summary }}</div>{% endif %}
{% if cv.skills %}<h2>{{ labels.skills }}</h2><div>{{ cv.skills | join(' • ') }}</div>{% endif %}
{% if cv.experience %}
<h2>{{ labels.experience }}</h2>
{% for job in cv.experience %}
<div class="entry">
<div class="entryhead"><span>{{ job.title }}{% if job.company %} — {{ job.company }}{% endif %}</span><span>{{ job.date }}</span></div>
{% if job.location %}<div class="small">{{ job.location }}</div>{% endif %}
{% if job.bullets %}<ul>{% for b in job.bullets %}<li>{{ b }}</li>{% endfor %}</ul>{% endif %}
</div>
{% endfor %}
{% endif %}
{% if cv.education %}
<h2>{{ labels.education }}</h2>
{% for edu in cv.education %}
<div class="entry"><div class="entryhead"><span>{{ edu.degree }}{% if edu.school %} — {{ edu.school }}{% endif %}</span><span>{{ edu.date }}</span></div>{% if edu.details %}<div class="small">{{ edu.details }}</div>{% endif %}</div>
{% endfor %}
{% endif %}
{% if cv.projects %}
<h2>{{ labels.projects }}</h2>
{% for p in cv.projects %}
<div class="entry"><div class="entryhead"><span>{{ p.name }}</span></div>{% if p.bullets %}<ul>{% for b in p.bullets %}<li>{{ b }}</li>{% endfor %}</ul>{% endif %}</div>
{% endfor %}
{% endif %}
</div>
</body>
</html>
"""
GERMAN_HINTS = {
"und", "mit", "für", "auf", "der", "die", "das", "ein", "eine", "sie", "wir", "nicht", "von",
"im", "ist", "sind", "bewerbung", "kenntnisse", "aufgaben", "profil", "studium", "erfahrung",
"anschreiben", "berufserfahrung", "ausbildung", "fähigkeiten", "wünschenswert", "unterstützen"
}
ENGLISH_HINTS = {
"the", "with", "for", "and", "you", "your", "experience", "skills", "responsibilities",
"application", "cover", "letter", "profile", "job", "support", "preferred", "education", "projects"
}
STOPWORDS = ENGLISH_HINTS | GERMAN_HINTS | {
"this", "that", "from", "into", "will", "have", "has", "our", "their", "they", "them", "about", "more", "than"
}
# =============================
# HELPERS
# =============================
def html_escape(text: Any) -> str:
if text is None:
return ""
s = str(text)
return (
s.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "'")
)
def normalize_space(text: str) -> str:
return re.sub(r"\s+", " ", text or "").strip()
def sentence_split(text: str) -> List[str]:
parts = re.split(r"(?<=[.!?])\s+|\n+", text or "")
return [normalize_space(p) for p in parts if normalize_space(p)]
def bulletize_lines(text: str) -> List[str]:
lines = [normalize_space(x) for x in (text or "").splitlines() if normalize_space(x)]
bullets = []
for line in lines:
cleaned = re.sub(r"^[\-•*]+\s*", "", line)
if len(cleaned) > 2:
bullets.append(cleaned)
return bullets
def tokenize(text: str) -> List[str]:
words = re.findall(r"[A-Za-zÄÖÜäöüß][A-Za-zÄÖÜäöüß0-9+.#\-/]*", (text or "").lower())
return [w for w in words if w not in STOPWORDS and len(w) > 2]
def extract_keywords(text: str, top_k: int = 40) -> List[str]:
counts: Dict[str, int] = {}
for tok in tokenize(text):
counts[tok] = counts.get(tok, 0) + 1
ranked = sorted(counts.items(), key=lambda x: (-x[1], x[0]))
return [k for k, _ in ranked[:top_k]]
def safe_json_loads(text: str) -> Optional[Any]:
try:
return json.loads(text)
except Exception:
pass
m = re.search(r"```json\s*(.*?)```", text or "", flags=re.S)
if m:
try:
return json.loads(m.group(1))
except Exception:
return None
return None
def ensure_list_of_strings(value: Any) -> List[str]:
if isinstance(value, list):
return [normalize_space(str(x)) for x in value if normalize_space(str(x))]
if normalize_space(str(value)):
return [normalize_space(str(value))]
return []
def detect_language_simple(text: str) -> str:
toks = tokenize(text)
de = sum(1 for t in toks if t in GERMAN_HINTS or any(ch in t for ch in "äöüß"))
en = sum(1 for t in toks if t in ENGLISH_HINTS)
return "de" if de > en else "en"
def read_pdf(file) -> str:
if pdfplumber is None:
raise RuntimeError("pdfplumber is not installed.")
parts = []
with pdfplumber.open(file) as pdf:
for page in pdf.pages:
try:
parts.append(page.extract_text() or "")
except Exception:
continue
return "\n".join(parts)
def read_docx(file) -> str:
if Document is None:
raise RuntimeError("python-docx is not installed.")
doc = Document(file)
return "\n".join(p.text for p in doc.paragraphs)
def read_text_file(uploaded_file) -> str:
name = uploaded_file.name.lower()
if name.endswith(".pdf"):
return read_pdf(uploaded_file)
if name.endswith(".docx"):
return read_docx(uploaded_file)
if name.endswith(".txt"):
return uploaded_file.read().decode("utf-8", errors="ignore")
raise ValueError("Unsupported file type. Use PDF, DOCX, or TXT.")
# =============================
# AI PROVIDERS
# =============================
class BaseProvider:
name = "base"
def generate_json(self, system_prompt: str, user_prompt: str) -> Dict[str, Any]:
raise NotImplementedError
class MockProvider(BaseProvider):
name = "mock"
def generate_json(self, system_prompt: str, user_prompt: str) -> Dict[str, Any]:
return {"mock": True}
class OpenAIProvider(BaseProvider):
name = "openai"
def __init__(self, api_key: str, model: str):
self.api_key = api_key
self.model = model
def generate_json(self, system_prompt: str, user_prompt: str) -> Dict[str, Any]:
from openai import OpenAI
client = OpenAI(api_key=self.api_key)
response = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
response_format={"type": "json_object"},
temperature=0.2,
)
content = response.choices[0].message.content
data = safe_json_loads(content)
if data is None:
raise RuntimeError(f"Provider returned non-JSON response:\n{content}")
return data
class GeminiProvider(BaseProvider):
name = "gemini"
def __init__(self, api_key: str, model: str):
self.api_key = api_key
self.model = model
def generate_json(self, system_prompt: str, user_prompt: str) -> Dict[str, Any]:
import google.generativeai as genai
genai.configure(api_key=self.api_key)
model = genai.GenerativeModel(self.model)
result = model.generate_content(system_prompt + "\n\n" + user_prompt + "\n\nReturn only valid JSON object.")
text = getattr(result, "text", "")
data = safe_json_loads(text)
if data is None:
raise RuntimeError(f"Provider returned non-JSON response:\n{text}")
return data
class ClaudeProvider(BaseProvider):
name = "claude"
def __init__(self, api_key: str, model: str):
self.api_key = api_key
self.model = model
def generate_json(self, system_prompt: str, user_prompt: str) -> Dict[str, Any]:
import anthropic
client = anthropic.Anthropic(api_key=self.api_key)
msg = client.messages.create(
model=self.model,
max_tokens=4000,
temperature=0.2,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt + "\n\nReturn only valid JSON object."}],
)
text = "".join(block.text for block in msg.content if getattr(block, "type", None) == "text")
data = safe_json_loads(text)
if data is None:
raise RuntimeError(f"Provider returned non-JSON response:\n{text}")
return data
def make_provider(provider_name: str, api_key: str, model: str) -> BaseProvider:
n = (provider_name or "").lower()
if n == "openai" and api_key:
return OpenAIProvider(api_key, model)
if n == "gemini" and api_key:
return GeminiProvider(api_key, model)
if n == "claude" and api_key:
return ClaudeProvider(api_key, model)
return MockProvider()
# =============================
# PARSING
# =============================
def split_sections(text: str) -> Dict[str, str]:
headers = [
"summary", "profile", "about", "profil", "zusammenfassung",
"experience", "work experience", "professional experience", "berufserfahrung", "erfahrung",
"education", "ausbildung", "studium",
"skills", "technical skills", "kenntnisse", "fähigkeiten",
"projects", "projekte",
]
current = "_top"
data: Dict[str, List[str]] = {current: []}
for line in (text or "").splitlines():
stripped = normalize_space(line)
lowered = stripped.lower().rstrip(":")
if lowered in headers:
current = lowered
data.setdefault(current, [])
else:
data.setdefault(current, []).append(line)
return {k: "\n".join(v).strip() for k, v in data.items()}
def parse_skills(text: str) -> List[str]:
if not text:
return []
parts = re.split(r"[,;|\n]", text)
out = []
for p in parts:
p = normalize_space(p)
if p and p not in out:
out.append(p)
return out[:40]
def parse_experience(text: str) -> List[Dict[str, Any]]:
if not text:
return []
blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()]
out = []
for block in blocks:
lines = [normalize_space(x) for x in block.splitlines() if normalize_space(x)]
title = lines[0] if lines else ""
company = lines[1] if len(lines) > 1 else ""
date = ""
bullets = []
for line in lines[2:]:
if re.search(r"\b(20\d{2}|19\d{2}|present|current|heute|jan|feb|mär|mar|apr|may|mai|jun|jul|aug|sep|oct|okt|nov|dec|dez)\b", line.lower()) and not date:
date = line
else:
bullets.append(re.sub(r"^[\-•*]+\s*", "", line))
if not bullets:
bullets = [re.sub(r"^[\-•*]+\s*", "", x) for x in lines[2:]]
out.append({
"company": company,
"title": title,
"date": date,
"location": "",
"bullets": bullets[:8],
})
return out[:10]
def parse_education(text: str) -> List[Dict[str, Any]]:
if not text:
return []
blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()]
out = []
for block in blocks:
lines = [normalize_space(x) for x in block.splitlines() if normalize_space(x)]
out.append({
"degree": lines[0] if len(lines) > 0 else "",
"school": lines[1] if len(lines) > 1 else "",
"date": lines[2] if len(lines) > 2 else "",
"details": "; ".join(lines[3:]) if len(lines) > 3 else "",
})
return out[:6]
def parse_projects(text: str) -> List[Dict[str, Any]]:
if not text:
return []
blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()]
out = []
for block in blocks:
lines = [normalize_space(x) for x in block.splitlines() if normalize_space(x)]
out.append({
"name": lines[0] if lines else "Project",
"bullets": [re.sub(r"^[\-•*]+\s*", "", x) for x in lines[1:]][:6],
})
return out[:8]
def parse_cv_heuristic(cv_text: str) -> Dict[str, Any]:
lines = [normalize_space(x) for x in (cv_text or "").splitlines() if normalize_space(x)]
top = lines[:8]
email_match = re.search(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", cv_text or "")
phone_match = re.search(r"(\+?\d[\d\s\-()]{7,}\d)", cv_text or "")
sections = split_sections(cv_text or "")
cv_lang = detect_language_simple(cv_text or "")
cv = {
"header": {
"name": top[0] if top else "Candidate Name",
"email": email_match.group(0) if email_match else "",
"phone": normalize_space(phone_match.group(1)) if phone_match else "",
"location": "",
"links": [],
},
"summary": normalize_space(
(
sections.get("summary", "") or sections.get("profile", "") or sections.get("about", "") or
sections.get("profil", "") or sections.get("zusammenfassung", "")
)[:700]
),
"skills": parse_skills(
sections.get("skills", "") or sections.get("technical skills", "") or
sections.get("kenntnisse", "") or sections.get("fähigkeiten", "")
),
"experience": parse_experience(
sections.get("experience", "") or sections.get("work experience", "") or
sections.get("professional experience", "") or sections.get("berufserfahrung", "") or
sections.get("erfahrung", "")
),
"education": parse_education(
sections.get("education", "") or sections.get("ausbildung", "") or sections.get("studium", "")
),
"projects": parse_projects(sections.get("projects", "") or sections.get("projekte", "")),
"language": cv_lang,
"raw_text": cv_text or "",
}
if not cv["skills"]:
cv["skills"] = extract_keywords(cv_text or "", top_k=20)
if not cv["experience"]:
bullets = bulletize_lines(cv_text or "")
if bullets:
cv["experience"] = [{
"company": "",
"title": "Experience Highlights",
"date": "",
"location": "",
"bullets": bullets[:8],
}]
return cv
def parse_job_description(jd_text: str) -> Dict[str, Any]:
jd_lang = detect_language_simple(jd_text or "")
keywords = extract_keywords(jd_text or "", top_k=50)
sentences = sentence_split(jd_text or "")
must_have: List[str] = []
nice_to_have: List[str] = []
responsibilities: List[str] = []
for s in sentences:
sl = s.lower()
if any(x in sl for x in ["must", "required", "requirement", "mandatory", "muss", "erforderlich", "voraussetzung"]):
must_have.append(s)
elif any(x in sl for x in ["preferred", "nice to have", "plus", "bonus", "wünschenswert"]):
nice_to_have.append(s)
elif any(x in sl for x in ["responsible", "you will", "tasks", "duties", "support", "design", "develop", "analyze", "manage", "create", "aufgaben", "sie unterstützen", "sie werden"]):
responsibilities.append(s)
return {
"language": jd_lang,
"keywords": keywords,
"must_have": must_have[:15],
"nice_to_have": nice_to_have[:15],
"responsibilities": responsibilities[:20],
"raw_text": jd_text or "",
}
# =============================
# SCORING
# =============================
def keyword_match_score(cv_text: str, jd_keywords: List[str]) -> Tuple[float, List[str], List[str]]:
cv_lower = (cv_text or "").lower()
found = [kw for kw in jd_keywords if kw.lower() in cv_lower]
missing = [kw for kw in jd_keywords if kw.lower() not in cv_lower]
score = 100.0 * len(found) / max(len(jd_keywords), 1)
return round(score, 1), found[:25], missing[:25]
def semantic_relevance_score(cv_text: str, jd_text: str) -> float:
cv_tokens = set(tokenize(cv_text or ""))
jd_tokens = set(tokenize(jd_text or ""))
inter = len(cv_tokens.intersection(jd_tokens))
union = max(len(cv_tokens.union(jd_tokens)), 1)
return round(100.0 * inter / union, 1)
def structure_score(cv: Dict[str, Any]) -> Tuple[float, List[str]]:
checks: List[str] = []
score = 0.0
if cv.get("header", {}).get("name"):
score += 10
else:
checks.append("Add your full name in the header.")
if cv.get("header", {}).get("email"):
score += 10
else:
checks.append("Add a professional email address.")
if cv.get("summary"):
score += 10
else:
checks.append("Add a short profile summary tailored to the job.")
if cv.get("skills"):
score += 15
else:
checks.append("Add a dedicated skills section.")
if cv.get("experience"):
score += 20
else:
checks.append("Add work experience or project experience.")
if cv.get("education"):
score += 10
else:
checks.append("Add your education section.")
if cv.get("projects"):
score += 10
quantified = 0
total = 0
for job in cv.get("experience", []):
if not isinstance(job, dict):
continue
for b in ensure_list_of_strings(job.get("bullets", [])):
total += 1
if re.search(r"\b\d+(?:[.,]\d+)?\b|%|hours|weeks|months|years|mm|cm|m\b|kg|€|eur|bar\b", b.lower()):
quantified += 1
if total:
score += min(15, (quantified / total) * 15)
else:
checks.append("Use bullet points under each experience entry.")
return round(min(score, 100), 1), checks
def composite_scores(cv: Dict[str, Any], jd: Dict[str, Any]) -> Dict[str, Any]:
kw, found, missing = keyword_match_score(cv.get("raw_text", ""), jd.get("keywords", []))
sem = semantic_relevance_score(cv.get("raw_text", ""), jd.get("raw_text", ""))
struct, notes = structure_score(cv)
ats1 = round(0.70 * kw + 0.30 * struct, 1)
ats2 = round(0.55 * sem + 0.45 * kw, 1)
ats3 = round(0.60 * struct + 0.40 * sem, 1)
workday = round(0.50 * struct + 0.35 * kw + 0.15 * sem, 1)
greenhouse = round(0.45 * sem + 0.30 * struct + 0.25 * kw, 1)
final = round((ats1 + ats2 + ats3 + workday + greenhouse) / 5.0, 1)
return {
"keyword_score": kw,
"semantic_score": sem,
"structure_score": struct,
"ats_source_1": ats1,
"ats_source_2": ats2,
"ats_source_3": ats3,
"workday_style_score": workday,
"greenhouse_style_score": greenhouse,
"final_score": final,
"found_keywords": found,
"missing_keywords": missing,
"structure_notes": notes,
}
# =============================
# SUGGESTIONS
# =============================
def build_bilingual_suggestion_prompt(cv: Dict[str, Any], jd: Dict[str, Any], truth_mode: str) -> Tuple[str, str]:
system_prompt = (
"You are a multilingual CV optimization assistant. Suggestion quality is extremely important. "
"The CV may be in German or English. The job description may be in German or English. "
"Internally understand both languages. Never invent experience, dates, tools, degrees, or achievements. "
"Return only JSON. Suggestions must be natural, concise, typo-free, and recruiter-friendly in both English and German."
)
user_prompt = f"""
Generate bilingual CV suggestions.
Truth mode: {truth_mode}
Rules:
1. Do not fabricate facts.
2. Only rewrite, reorder, clarify, or highlight existing evidence.
3. Add job-description keywords only if supported by the CV.
4. Rewrite only summary text, skill entries, or bullet points.
5. Produce both English and German suggestion text.
6. Keep each suggestion high quality.
Return JSON with this exact structure:
{{
"suggestions": [
{{
"id": "unique_id",
"type": "rewrite|add_summary|add_skill|project_highlight",
"section": "summary|skills|experience|projects",
"target_path": "example: experience.0.bullets.1",
"reason_en": "why this helps",
"reason_de": "warum das hilft",
"old_text": "old text or empty",
"suggested_text_en": "English version",
"suggested_text_de": "German version",
"tags": ["keyword", "clarity", "structure"]
}}
]
}}
CURRENT CV JSON:
{json.dumps(cv, ensure_ascii=False, indent=2)}
JOB DESCRIPTION JSON:
{json.dumps(jd, ensure_ascii=False, indent=2)}
"""
return system_prompt, user_prompt
def heuristic_suggestions(cv: Dict[str, Any], jd: Dict[str, Any], scores: Dict[str, Any]) -> List[Dict[str, Any]]:
suggestions: List[Dict[str, Any]] = []
missing = scores.get("missing_keywords", [])[:8]
if not cv.get("summary"):
suggestions.append({
"id": str(uuid.uuid4()),
"type": "add_summary",
"section": "summary",
"target_path": "summary",
"reason_en": "Adds a targeted profile summary.",
"reason_de": "Ergänzt ein zielgerichtetes Kurzprofil.",
"old_text": "",
"suggested_text_en": "Candidate with hands-on project and technical documentation experience, aligned with the target role.",
"suggested_text_de": "Kandidat mit praktischer Projekt- und technischer Dokumentationserfahrung, passend zur Zielposition.",
"tags": ["structure"],
})
existing = {x.lower() for x in ensure_list_of_strings(cv.get("skills", []))}
for kw in missing[:5]:
if kw.lower() not in existing:
suggestions.append({
"id": str(uuid.uuid4()),
"type": "add_skill",
"section": "skills",
"target_path": "skills",
"reason_en": "This keyword appears in the job description and may improve matching if accurate.",
"reason_de": "Dieses Stichwort kommt in der Stellenanzeige vor und kann die Passung verbessern, falls es zutrifft.",
"old_text": "",
"suggested_text_en": kw,
"suggested_text_de": kw,
"tags": ["keyword"],
})
return suggestions
def validate_suggestion_record(s: Any) -> Optional[Dict[str, Any]]:
if not isinstance(s, dict):
return None
target_path = str(s.get("target_path", "")).strip()
allowed = (
target_path == "summary" or
target_path == "skills" or
(target_path.startswith("experience.") and ".bullets." in target_path) or
(target_path.startswith("projects.") and ".bullets." in target_path)
)
if not allowed:
return None
en = normalize_space(str(s.get("suggested_text_en", "")))
de = normalize_space(str(s.get("suggested_text_de", "")))
if not en or not de:
return None
out = dict(s)
out["id"] = str(out.get("id") or uuid.uuid4())
out["reason_en"] = normalize_space(str(out.get("reason_en", "")))
out["reason_de"] = normalize_space(str(out.get("reason_de", "")))
out["suggested_text_en"] = en
out["suggested_text_de"] = de
out["tags"] = [str(x) for x in out.get("tags", [])] if isinstance(out.get("tags", []), list) else []
return out
def generate_suggestions(cv: Dict[str, Any], jd: Dict[str, Any], provider: BaseProvider, truth_mode: str, scores: Dict[str, Any]) -> List[Dict[str, Any]]:
heuristic = heuristic_suggestions(cv, jd, scores)
if isinstance(provider, MockProvider):
return heuristic
try:
system_prompt, user_prompt = build_bilingual_suggestion_prompt(cv, jd, truth_mode)
data = provider.generate_json(system_prompt, user_prompt)
llm = data.get("suggestions", []) if isinstance(data, dict) else []
merged: List[Dict[str, Any]] = []
seen = set()
for raw in llm + heuristic:
v = validate_suggestion_record(raw)
if not v:
continue
key = json.dumps(
{"target_path": v["target_path"], "en": v["suggested_text_en"], "de": v["suggested_text_de"]},
ensure_ascii=False,
sort_keys=True,
)
if key not in seen:
seen.add(key)
merged.append(v)
return merged[:35]
except Exception as e:
st.warning(f"AI provider failed, using heuristic suggestions. Details: {e}")
return heuristic
# =============================
# APPLY SUGGESTIONS
# =============================
def set_path_value(data: Dict[str, Any], path: str, value: Any):
parts = path.split(".")
cur: Any = data
for part in parts[:-1]:
cur = cur[int(part)] if part.isdigit() else cur[part]
last = parts[-1]
if last.isdigit():
cur[int(last)] = value
else:
cur[last] = value
def structured_cv_to_text(cv: Dict[str, Any]) -> str:
parts: List[str] = []
hdr = cv.get("header", {}) if isinstance(cv.get("header", {}), dict) else {}
parts.extend([
str(hdr.get("name", "")),
str(hdr.get("email", "")),
str(hdr.get("phone", "")),
str(hdr.get("location", "")),
])
if cv.get("summary"):
parts.extend(["Summary", str(cv.get("summary", ""))])
if cv.get("skills"):
parts.extend(["Skills", ", ".join(ensure_list_of_strings(cv.get("skills", [])))])
if cv.get("experience"):
parts.append("Experience")
for job in cv.get("experience", []):
if isinstance(job, dict):
parts.extend([
str(job.get("title", "")),
str(job.get("company", "")),
str(job.get("date", "")),
str(job.get("location", "")),
])
parts.extend(ensure_list_of_strings(job.get("bullets", [])))
else:
parts.append(str(job))
if cv.get("education"):
parts.append("Education")
for edu in cv.get("education", []):
if isinstance(edu, dict):
parts.extend([
str(edu.get("degree", "")),
str(edu.get("school", "")),
str(edu.get("date", "")),
str(edu.get("details", "")),
])
else:
parts.append(str(edu))
if cv.get("projects"):
parts.append("Projects")
for p in cv.get("projects", []):
if isinstance(p, dict):
parts.append(str(p.get("name", "")))
parts.extend(ensure_list_of_strings(p.get("bullets", [])))
else:
parts.append(str(p))
return "\n".join(normalize_space(x) for x in parts if normalize_space(x))
def apply_suggestions(cv: Dict[str, Any], suggestions: List[Dict[str, Any]], accepted_ids: List[str], language: str = "en") -> Dict[str, Any]:
new_cv = json.loads(json.dumps(cv))
accepted = [s for s in suggestions if isinstance(s, dict) and s.get("id") in accepted_ids]
text_key = "suggested_text_de" if language == "de" else "suggested_text_en"
for s in accepted:
tp = s.get("type")
path = str(s.get("target_path", "")).strip()
text = s.get(text_key, "")
try:
if tp == "rewrite" and path.startswith("experience.") and ".bullets." in path:
set_path_value(new_cv, path, text)
elif tp == "rewrite" and path.startswith("projects.") and ".bullets." in path:
set_path_value(new_cv, path, text)
elif tp == "project_highlight" and path.startswith("projects.") and ".bullets." in path:
set_path_value(new_cv, path, text)
elif tp == "add_summary" and path == "summary":
new_cv["summary"] = text
elif tp == "add_skill" and path == "skills":
if text and text not in new_cv.get("skills", []):
new_cv.setdefault("skills", []).append(text)
except Exception:
continue
new_cv["raw_text"] = structured_cv_to_text(new_cv)
return new_cv
# =============================
# FINAL PACKAGE GENERATION
# =============================
def build_bilingual_application_prompt(
cv_text: str,
jd_text: str,
cv_lang: str,
jd_lang: str,
suggestions: List[Dict[str, Any]],
accepted_ids: List[str],
cover_inputs: Dict[str, str],
) -> Tuple[str, str]:
accepted = [s for s in suggestions if isinstance(s, dict) and s.get("id") in accepted_ids]
system_prompt = (
"You are a senior multilingual CV and cover-letter editor. The CV may be in German or English. The job description may be in German or English. "
"Internally understand both languages. Never invent facts. Generate polished output in BOTH English and German. Return only JSON."
)
user_prompt = f"""
Create final bilingual application materials.
Rules:
1. Detect the language of the CV and the job description.
2. Internally translate as needed for analysis.
3. Preserve all facts from the original CV.
4. Apply the accepted suggestions naturally.
5. Produce final CV text in English and German.
6. Produce final cover letter in English and German.
7. Cover letters must use the user inputs naturally.
8. Also create one long reusable external prompt for OpenAI/Gemini/Claude.
Return JSON with this exact structure:
{{
"detected": {{"cv_language": "en|de", "jd_language": "en|de"}},
"cv_en": {{"header": {{}}, "summary": "", "skills": [], "experience": [], "education": [], "projects": []}},
"cv_de": {{"header": {{}}, "summary": "", "skills": [], "experience": [], "education": [], "projects": []}},
"cover_letter_en": "full letter",
"cover_letter_de": "full letter",
"external_prompt": "long reusable prompt"
}}
Current CV text:
{cv_text}
Job description text:
{jd_text}
Known detected languages:
CV language: {cv_lang}
JD language: {jd_lang}
Accepted suggestions:
{json.dumps(accepted, ensure_ascii=False, indent=2)}
Cover-letter user inputs:
{json.dumps(cover_inputs, ensure_ascii=False, indent=2)}
"""
return system_prompt, user_prompt
def call_provider_text(provider: BaseProvider, system_prompt: str, user_prompt: str) -> str:
"""
Ask the provider for plain text instead of JSON.
"""
if isinstance(provider, MockProvider):
return ""
try:
if isinstance(provider, OpenAIProvider):
from openai import OpenAI
client = OpenAI(api_key=provider.api_key)
response = client.chat.completions.create(
model=provider.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=0.2,
)
return response.choices[0].message.content or ""
if isinstance(provider, GeminiProvider):
import google.generativeai as genai
genai.configure(api_key=provider.api_key)
model = genai.GenerativeModel(provider.model)
result = model.generate_content(system_prompt + "\n\n" + user_prompt)
return getattr(result, "text", "") or ""
if isinstance(provider, ClaudeProvider):
import anthropic
client = anthropic.Anthropic(api_key=provider.api_key)
msg = client.messages.create(
model=provider.model,
max_tokens=4000,
temperature=0.2,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
)
return "".join(
block.text for block in msg.content if getattr(block, "type", None) == "text"
)
except Exception as e:
raise RuntimeError(str(e))
return ""
def build_final_cv_text_prompt(
cv_text: str,
jd_text: str,
accepted_suggestions: List[Dict[str, Any]],
) -> Tuple[str, str]:
system_prompt = (
"You are a senior multilingual CV writer. "
"The CV may be in German or English. The job description may be in German or English. "
"Understand both languages. Never invent facts. "
"Write polished final CVs in English and German. "
"Return plain text only, no JSON, no markdown code fences."
)
user_prompt = f"""
Create final CV versions in BOTH English and German.
Rules:
1. Do not invent any experience, dates, skills, metrics, or achievements.
2. Only use facts already present in the CV and accepted suggestions.
3. Improve wording, clarity, ATS alignment, and professionalism.
4. Keep the writing natural and recruiter-friendly.
5. Output plain text only.
Original CV:
{cv_text}
Job Description:
{jd_text}
Accepted Suggestions:
{json.dumps(accepted_suggestions, ensure_ascii=False, indent=2)}
Return in this exact format:
=== FINAL CV ENGLISH ===
<final CV in English>
=== FINAL CV GERMAN ===
<final CV in German>
"""
return system_prompt, user_prompt
def build_cover_letter_text_prompt(
cv_text: str,
jd_text: str,
accepted_suggestions: List[Dict[str, Any]],
cover_inputs: Dict[str, str],
) -> Tuple[str, str]:
system_prompt = (
"You are a senior multilingual cover-letter writer. "
"The CV may be in German or English. The job description may be in German or English. "
"Understand both languages. Never invent facts. "
"Write polished final cover letters in English and German. "
"Return plain text only, no JSON, no markdown code fences."
)
user_prompt = f"""
Create final cover letters in BOTH English and German.
Rules:
1. Do not invent experience, achievements, tools, or claims not supported by the CV.
2. Use the user inputs naturally.
3. Tailor both letters to the job description.
4. Make the German version proper business German, not literal translation.
5. Output plain text only.
Original CV:
{cv_text}
Job Description:
{jd_text}
Accepted Suggestions:
{json.dumps(accepted_suggestions, ensure_ascii=False, indent=2)}
Cover Letter Inputs:
{json.dumps(cover_inputs, ensure_ascii=False, indent=2)}
Return in this exact format:
=== COVER LETTER ENGLISH ===
<cover letter in English>
=== COVER LETTER GERMAN ===
<cover letter in German>
"""
return system_prompt, user_prompt