@yottameta/yotta-resume 0.0.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1220 @@
1
+ #!/usr/bin/env python3
2
+ """yotta-resume: local resume analysis, follow-up questions, and document export."""
3
+
4
+ import argparse
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import zipfile
14
+ from pathlib import Path
15
+ from xml.etree import ElementTree
16
+
17
+ from contract_validate import validate_contracts
18
+
19
+ try:
20
+ sys.stdout.reconfigure(encoding="utf-8")
21
+ sys.stderr.reconfigure(encoding="utf-8")
22
+ except Exception:
23
+ pass
24
+
25
+
26
+ VERSION = "0.1.2"
27
+ SCHEMA_VERSION = "1.1"
28
+
29
+ _PHONE_RE = re.compile(r"(?<!\d)1[3-9]\d{9}(?!\d)")
30
+ _EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
31
+ _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
32
+ _BULLET_RE = re.compile(r"^\s*(?:[-*+]\s+|\d+[.、)]\s+)(.+)$")
33
+ _PLACEHOLDER_RE = re.compile(
34
+ r"(?<![A-Za-z0-9])(?:x{2,}|X{2,}|待填|TO" r"DO|TBD)(?![A-Za-z0-9])",
35
+ re.IGNORECASE,
36
+ )
37
+ _LONG_TOKEN_RE = re.compile(r"\b[A-Za-z0-9_]{18,}\b")
38
+
39
+ _JD_KEYWORDS = (
40
+ "SIEM",
41
+ "Python",
42
+ "SQL",
43
+ "Linux",
44
+ "MITRE ATT&CK",
45
+ "OWASP",
46
+ "SOC",
47
+ "EDR",
48
+ "应急响应",
49
+ "漏洞管理",
50
+ )
51
+
52
+ _SECTION_ALIASES = {
53
+ "工作经历": "experience",
54
+ "工作经验": "experience",
55
+ "实习经历": "experience",
56
+ "项目经历": "projects",
57
+ "项目经验": "projects",
58
+ "技能": "skills",
59
+ "专业技能": "skills",
60
+ "教育背景": "education",
61
+ "教育经历": "education",
62
+ "求职意向": "intent",
63
+ "相关技能": "skills",
64
+ "SRC 挖掘": "src",
65
+ "SRC挖掘": "src",
66
+ "自我评价": "self_evaluation",
67
+ }
68
+
69
+
70
+ class ResumeInputError(Exception):
71
+ """A controlled, user-facing input parse failure."""
72
+
73
+ def __init__(self, message, exit_code=5):
74
+ super().__init__(message)
75
+ self.exit_code = exit_code
76
+
77
+
78
+ def _mask_contact(text):
79
+ """Mask direct contact channels while retaining useful diagnostic wording."""
80
+ text = _PHONE_RE.sub("[电话]", text)
81
+ return _EMAIL_RE.sub("[邮箱]", text)
82
+
83
+
84
+ def _masked(original):
85
+ return _mask_contact(original.strip()) or "[空内容]"
86
+
87
+
88
+ def _normalise_plain_resume(text):
89
+ """Restore section markers for text extracted from PDF or DOCX."""
90
+ known_titles = set(_SECTION_ALIASES) | {
91
+ "个人简介",
92
+ "简介",
93
+ "个人总结",
94
+ "总结",
95
+ }
96
+ lines = []
97
+ new_field_prefixes = (
98
+ "电话",
99
+ "邮箱",
100
+ "性别",
101
+ "户籍",
102
+ "最高学历",
103
+ "毕业时间",
104
+ "意向岗位",
105
+ "意向城市",
106
+ "期望薪资",
107
+ "求职类型",
108
+ "期望行业",
109
+ "当前状态",
110
+ )
111
+
112
+ def starts_entry(value):
113
+ return bool(
114
+ _BULLET_RE.match(value)
115
+ or re.match(r"^20\d{2}[./年-]\d{1,2}", value)
116
+ or " | " in value
117
+ or value.startswith(new_field_prefixes)
118
+ )
119
+
120
+ for raw_line in text.splitlines():
121
+ stripped = raw_line.strip()
122
+ if not stripped:
123
+ lines.append("")
124
+ continue
125
+ if stripped in known_titles:
126
+ lines.append("## " + stripped)
127
+ elif _HEADING_RE.match(stripped):
128
+ lines.append(stripped)
129
+ elif starts_entry(stripped) or not lines:
130
+ lines.append(stripped)
131
+ else:
132
+ previous = lines[-1]
133
+ if not previous or previous.startswith("#"):
134
+ lines.append(stripped)
135
+ elif previous[-1].isascii() and previous[-1].isalnum() and stripped[0].isascii() and stripped[0].isalnum():
136
+ lines[-1] = previous + " " + stripped
137
+ else:
138
+ lines[-1] = previous + stripped
139
+ return "\n".join(lines).strip()
140
+
141
+
142
+ def _sha256_file(path):
143
+ digest = hashlib.sha256()
144
+ with Path(path).open("rb") as handle:
145
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
146
+ digest.update(chunk)
147
+ return digest.hexdigest().upper()
148
+
149
+
150
+ def _year_month_match(pattern, text):
151
+ match = re.search(pattern, text, re.MULTILINE)
152
+ if not match:
153
+ return None
154
+ year = int(match.group(1))
155
+ month = int(match.group(2))
156
+ if not 1 <= month <= 12:
157
+ return None
158
+ return year * 12 + month
159
+
160
+
161
+ def _date_conflict(text):
162
+ declared = _year_month_match(
163
+ r"毕业时间\s*[::]\s*(20\d{2})[./年-](\d{1,2})",
164
+ text,
165
+ )
166
+ education_end = None
167
+ match = re.search(
168
+ r"教育(?:背景|经历)[\s\S]{0,220}?"
169
+ r"(20\d{2})[./年-](\d{1,2})[^\n]{0,24}?"
170
+ r"(?:-|–|—|至|到)\s*"
171
+ r"(20\d{2})[./年-](\d{1,2})",
172
+ text,
173
+ re.MULTILINE,
174
+ )
175
+ if match and 1 <= int(match.group(4)) <= 12:
176
+ education_end = int(match.group(3)) * 12 + int(match.group(4))
177
+ if declared is not None and education_end is not None and declared != education_end:
178
+ return True
179
+ return False
180
+
181
+
182
+ def _finding(code, section, heading, original, reason, severity="medium", needs_confirmation=False):
183
+ return {
184
+ "id": "",
185
+ "code": code,
186
+ "section": section,
187
+ "heading": heading,
188
+ "original": _masked(original),
189
+ "reason": reason,
190
+ "severity": severity,
191
+ "source_type": "rule",
192
+ "needs_confirmation": needs_confirmation,
193
+ }
194
+
195
+
196
+ def _assign_finding_ids(issues):
197
+ for index, issue in enumerate(issues, 1):
198
+ issue["id"] = "YS-{:03d}".format(index)
199
+ return issues
200
+
201
+
202
+ def parse_markdown_resume(markdown):
203
+ """Parse a simple Markdown resume into a stable content model."""
204
+ lines = markdown.splitlines()
205
+ model = {
206
+ "schema_version": SCHEMA_VERSION,
207
+ "name": "",
208
+ "headline": "",
209
+ "contact": [],
210
+ "summary": "",
211
+ "sections": [],
212
+ }
213
+ current_section = None
214
+ current_item = None
215
+ summary_lines = []
216
+
217
+ for raw_line in lines:
218
+ line = raw_line.rstrip()
219
+ match = _HEADING_RE.match(line)
220
+ if match:
221
+ level = len(match.group(1))
222
+ title = match.group(2).strip()
223
+ if level == 1 and not model["name"]:
224
+ model["name"] = title
225
+ current_section = None
226
+ current_item = None
227
+ continue
228
+ if level == 2:
229
+ if title in {"个人简介", "简介", "个人总结", "总结"}:
230
+ current_section = "summary"
231
+ else:
232
+ current_section = {"title": title, "items": []}
233
+ model["sections"].append(current_section)
234
+ current_item = None
235
+ continue
236
+ if level >= 3 and current_section and current_section != "summary":
237
+ current_item = {"heading": title, "bullets": []}
238
+ current_section["items"].append(current_item)
239
+ continue
240
+ if level >= 3:
241
+ continue
242
+
243
+ bullet = _BULLET_RE.match(line)
244
+ if bullet:
245
+ content = bullet.group(1).strip()
246
+ if current_section == "summary":
247
+ summary_lines.append(content)
248
+ elif current_item is not None:
249
+ current_item["bullets"].append(content)
250
+ elif current_section:
251
+ current_section["items"].append({"heading": "", "bullets": [content]})
252
+ continue
253
+
254
+ if line.strip():
255
+ if current_section == "summary":
256
+ summary_lines.append(line.strip())
257
+ elif current_section is None:
258
+ for part in re.split(r"[||;;,,\s]+", line.strip()):
259
+ if part:
260
+ model["contact"].append(part)
261
+ elif current_section:
262
+ if not current_section["items"]:
263
+ current_section["items"].append({"heading": "", "bullets": []})
264
+ current_section["items"][-1]["bullets"].append(line.strip())
265
+
266
+ model["summary"] = "\n".join(summary_lines).strip()
267
+ return model
268
+
269
+
270
+ def _bullet_texts(model):
271
+ for section in model.get("sections", []):
272
+ for item in section.get("items", []):
273
+ for bullet in item.get("bullets", []):
274
+ yield section.get("title", ""), item.get("heading", ""), bullet
275
+
276
+
277
+ def _has_metric(text):
278
+ return bool(
279
+ re.search(r"\d+(?:\.\d+)?\s*(?:%|%|倍|x|X|次|个|条|台|天|小时|分钟|人|万|k|K)", text)
280
+ )
281
+
282
+
283
+ def _jd_match(resume, jd):
284
+ if not jd.strip():
285
+ return {
286
+ "matched": [],
287
+ "missing": [],
288
+ "coverage": None,
289
+ "status": "not_provided",
290
+ "note": "未提供目标 JD,不能判断岗位匹配。",
291
+ }
292
+ haystack = resume.lower()
293
+ matched = []
294
+ missing = []
295
+ for keyword in _JD_KEYWORDS:
296
+ if keyword.lower() in haystack:
297
+ matched.append(keyword)
298
+ elif jd and keyword.lower() in jd.lower():
299
+ missing.append(keyword)
300
+ total = len(matched) + len(missing)
301
+ coverage = round(100 * len(matched) / total, 1) if total else 0.0
302
+ return {
303
+ "matched": matched,
304
+ "missing": missing,
305
+ "coverage": coverage,
306
+ "status": "matched",
307
+ "note": "",
308
+ }
309
+
310
+
311
+ def _build_issues(model, bullets, has_jd, text="", source_manifest=None):
312
+ source_manifest = source_manifest or {}
313
+ issues = []
314
+ weak_claims = []
315
+ no_metric = []
316
+ for section, heading, bullet in bullets:
317
+ if any(word in bullet for word in ("负责", "参与", "协助", "熟悉", "沟通能力强", "认真")) and not _has_metric(bullet):
318
+ weak_claims.append((section, heading, bullet))
319
+ elif not _has_metric(bullet) and any(word in bullet for word in ("提升", "优化", "减少", "建设", "处置", "分析")):
320
+ no_metric.append((section, heading, bullet))
321
+
322
+ for section, heading, bullet in weak_claims:
323
+ issues.append(_finding(
324
+ "weak_claim",
325
+ section,
326
+ heading,
327
+ bullet,
328
+ "职责描述缺少结果或个人边界,读者无法判断贡献质量。",
329
+ ))
330
+ for section, heading, bullet in no_metric:
331
+ issues.append(_finding(
332
+ "missing_metric",
333
+ section,
334
+ heading,
335
+ bullet,
336
+ "有效改进缺少基线、规模或结果指标。",
337
+ ))
338
+
339
+ if _PLACEHOLDER_RE.search(text):
340
+ placeholder = _PLACEHOLDER_RE.search(text).group(0)
341
+ issues.append(_finding(
342
+ "placeholder",
343
+ "全文",
344
+ "",
345
+ placeholder,
346
+ "检测到未填写的占位符,成果口径不完整。",
347
+ severity="high",
348
+ ))
349
+ if text.count("意向岗位") > 1:
350
+ issues.append(_finding(
351
+ "duplicate_field",
352
+ "求职意向",
353
+ "",
354
+ "意向岗位出现多次",
355
+ "同一求职字段重复,容易造成信息冗余或口径不一致。",
356
+ ))
357
+ if _date_conflict(text):
358
+ issues.append(_finding(
359
+ "date_conflict",
360
+ "教育经历",
361
+ "",
362
+ "毕业时间与教育起止时间不一致",
363
+ "文本中的毕业月份和教育结束月份冲突,需要用户确认唯一口径。",
364
+ severity="high",
365
+ needs_confirmation=True,
366
+ ))
367
+ if "精通" in text and "了解" in text:
368
+ issues.append(_finding(
369
+ "mixed_skill_levels",
370
+ "技能",
371
+ "",
372
+ "同时出现「精通」与「了解」",
373
+ "能力等级跨度大,需确认是否有足够证据支撑高等级表述。",
374
+ needs_confirmation=True,
375
+ ))
376
+
377
+ token_counts = {}
378
+ for token in _LONG_TOKEN_RE.findall(text):
379
+ token_counts[token] = token_counts.get(token, 0) + 1
380
+ repeated = [token for token, count in token_counts.items() if count >= 3]
381
+ if repeated:
382
+ token = repeated[0]
383
+ issues.append(_finding(
384
+ "template_watermark",
385
+ "输入文件",
386
+ "",
387
+ "重复模板串:{}...".format(token[:16]),
388
+ "长字符串在简历中重复出现,可能是模板水印或导出残留。",
389
+ severity="high",
390
+ needs_confirmation=True,
391
+ ))
392
+
393
+ image_count = int(source_manifest.get("images") or 0)
394
+ if image_count > 0:
395
+ issues.append(_finding(
396
+ "image_text_gap",
397
+ "输入文件",
398
+ "",
399
+ "PDF 含 {} 张图片,未执行 OCR。".format(image_count),
400
+ "图片内的证书、成绩或成果不会进入文本分析。",
401
+ needs_confirmation=True,
402
+ ))
403
+
404
+ if model.get("contact"):
405
+ issues.append(_finding(
406
+ "sensitive_contact",
407
+ "联系方式",
408
+ "",
409
+ "联系方式已识别:[电话] / [邮箱]",
410
+ "分析报告只保留联系方式类型,不回显手机号或邮箱原文。",
411
+ ))
412
+ if has_jd and not model.get("summary"):
413
+ issues.append(_finding(
414
+ "missing_summary",
415
+ "个人简介",
416
+ "",
417
+ "[空内容]",
418
+ "缺少面向岗位的简介,招聘方难以快速定位候选方向。",
419
+ ))
420
+ return _assign_finding_ids(issues)
421
+
422
+
423
+ def _build_questions(issues, jd):
424
+ questions = [
425
+ {
426
+ "target": "impact",
427
+ "question": "请补充这条工作的规模和结果:覆盖多少资产 / 日志量 / 告警量,最终效率或风险指标变化多少?",
428
+ "why": "把职责描述转为可验证证据。",
429
+ },
430
+ {
431
+ "target": "ownership",
432
+ "question": "这项工作是你独立负责、牵头还是参与?请说明分工边界和个人动作。",
433
+ "why": "避免团队成果被误写成个人成果。",
434
+ },
435
+ ]
436
+ if any(issue["code"] == "sensitive_contact" for issue in issues):
437
+ questions.append({
438
+ "target": "privacy",
439
+ "question": "导出的正式简历会保留联系方式,但分析报告会打码。请确认联系方式是否为本人真实信息。",
440
+ "why": "防止误用他人联系方式或泄露敏感信息。",
441
+ })
442
+ if jd and ("MITRE ATT&CK" in jd or "OWASP" in jd):
443
+ questions.append({
444
+ "target": "jd_gap",
445
+ "question": "JD 提到 MITRE ATT&CK / OWASP,你是否在真实项目里用过?请给出对应场景和动作。",
446
+ "why": "补齐岗位关键词必须基于真实经历。",
447
+ })
448
+ return questions
449
+
450
+
451
+ def _build_suggestions(issues, jd_match):
452
+ suggestions = []
453
+ for issue in issues:
454
+ if issue["code"] == "weak_claim":
455
+ suggestions.append({
456
+ "code": "rewrite_weak_claim",
457
+ "finding_id": issue["id"],
458
+ "original": issue["original"],
459
+ "suggestion": "改写为「我的动作 + 工具/流程 + 规模 + 结果」,例如:独立处置 X 类告警 Y 条/日,通过 Z 规则将重复告警降低 N%。",
460
+ "priority": "high",
461
+ })
462
+ elif issue["code"] == "missing_metric":
463
+ suggestions.append({
464
+ "code": "add_metric",
465
+ "finding_id": issue["id"],
466
+ "original": issue["original"],
467
+ "suggestion": "保留真实口径:补充优化前基线、优化后结果、时间范围或覆盖规模;不能编造数字。",
468
+ "priority": "high",
469
+ })
470
+ elif issue["code"] == "sensitive_contact":
471
+ suggestions.append({
472
+ "code": "protect_contact",
473
+ "finding_id": issue["id"],
474
+ "original": issue["original"],
475
+ "suggestion": "联系方式只出现在正式简历,不出现在分享给他人的分析报告。",
476
+ "priority": "medium",
477
+ })
478
+ elif issue["code"] == "missing_summary":
479
+ suggestions.append({
480
+ "code": "add_summary",
481
+ "finding_id": issue["id"],
482
+ "original": issue["original"],
483
+ "suggestion": "在简介写 2-3 句:安全方向、核心经验、代表性成果和目标岗位。",
484
+ "priority": "medium",
485
+ })
486
+ elif issue["code"] == "placeholder":
487
+ suggestions.append({
488
+ "code": "fill_placeholder",
489
+ "finding_id": issue["id"],
490
+ "original": issue["original"],
491
+ "suggestion": "填写真实数据;无法确认时删除该分句,不能保留 xx 或待填标记。",
492
+ "priority": "high",
493
+ })
494
+ elif issue["code"] == "duplicate_field":
495
+ suggestions.append({
496
+ "code": "deduplicate_field",
497
+ "finding_id": issue["id"],
498
+ "original": issue["original"],
499
+ "suggestion": "保留一处求职意向,其他位置改为岗位方向或删除。",
500
+ "priority": "medium",
501
+ })
502
+ elif issue["code"] == "date_conflict":
503
+ suggestions.append({
504
+ "code": "confirm_dates",
505
+ "finding_id": issue["id"],
506
+ "original": issue["original"],
507
+ "suggestion": "确认毕业月份、教育起止和入职性质,全篇统一为一个口径。",
508
+ "priority": "high",
509
+ })
510
+ elif issue["code"] == "mixed_skill_levels":
511
+ suggestions.append({
512
+ "code": "normalise_skill_levels",
513
+ "finding_id": issue["id"],
514
+ "original": issue["original"],
515
+ "suggestion": "按真实掌握程度统一为熟悉 / 掌握 / 了解;没有项目证据时不要写精通。",
516
+ "priority": "medium",
517
+ })
518
+ elif issue["code"] == "template_watermark":
519
+ suggestions.append({
520
+ "code": "remove_watermark",
521
+ "finding_id": issue["id"],
522
+ "original": issue["original"],
523
+ "suggestion": "使用无水印模板重新导出,并确认文本层不再包含模板串。",
524
+ "priority": "high",
525
+ })
526
+ elif issue["code"] == "image_text_gap":
527
+ suggestions.append({
528
+ "code": "move_image_text_to_text",
529
+ "finding_id": issue["id"],
530
+ "original": issue["original"],
531
+ "suggestion": "把关键证书、成绩和成果转成可检索文字;图片只作装饰。",
532
+ "priority": "medium",
533
+ })
534
+
535
+ for keyword in jd_match.get("missing", []):
536
+ suggestions.append({
537
+ "code": "jd_gap",
538
+ "original": "JD 关键词缺失:{}".format(keyword),
539
+ "suggestion": "只在真实项目里补写该关键词;没有经历就不要硬写。",
540
+ "priority": "medium",
541
+ })
542
+ if not suggestions:
543
+ suggestions.append({
544
+ "code": "keep_evidence",
545
+ "original": "当前简历已有基础结构和经历描述。",
546
+ "suggestion": "继续保留事实口径,并优先检查每条经历的量化证据。",
547
+ "priority": "low",
548
+ })
549
+ return suggestions
550
+
551
+
552
+ def _build_structure_check(sections, bullet_count, metric_count, issues, jd_match):
553
+ required_sections = ("experience", "skills", "education")
554
+ present_sections = sum(1 for item in required_sections if item in sections)
555
+ section_score = round(100 * present_sections / len(required_sections))
556
+ metric_ratio = round(100 * metric_count / bullet_count, 1) if bullet_count else 0.0
557
+ evidence_score = round(min(100.0, metric_ratio))
558
+ high_count = sum(1 for item in issues if item.get("severity") == "high")
559
+ medium_count = sum(1 for item in issues if item.get("severity") == "medium")
560
+ hygiene_score = max(0, 100 - high_count * 20 - medium_count * 8)
561
+
562
+ dimensions = [
563
+ {
564
+ "key": "sections",
565
+ "label": "章节结构",
566
+ "score": section_score,
567
+ "weight": 25,
568
+ "evidence": "工作经历 / 技能 / 教育背景:{}/{}".format(
569
+ present_sections, len(required_sections)
570
+ ),
571
+ },
572
+ {
573
+ "key": "quantitative_evidence",
574
+ "label": "量化证据",
575
+ "score": evidence_score,
576
+ "weight": 35,
577
+ "evidence": "含指标要点 {} / {}".format(metric_count, bullet_count),
578
+ },
579
+ {
580
+ "key": "hygiene",
581
+ "label": "文本清洁度",
582
+ "score": hygiene_score,
583
+ "weight": 25,
584
+ "evidence": "high {} 项 / medium {} 项".format(high_count, medium_count),
585
+ },
586
+ ]
587
+ if jd_match.get("status") == "matched" and jd_match.get("coverage") is not None:
588
+ dimensions.append({
589
+ "key": "jd_match",
590
+ "label": "JD 关键词匹配",
591
+ "score": round(float(jd_match["coverage"])),
592
+ "weight": 15,
593
+ "evidence": "命中 {} / 缺失 {}".format(
594
+ len(jd_match.get("matched", [])),
595
+ len(jd_match.get("missing", [])),
596
+ ),
597
+ })
598
+
599
+ total_weight = sum(item["weight"] for item in dimensions)
600
+ score = round(
601
+ sum(item["score"] * item["weight"] for item in dimensions) / total_weight
602
+ )
603
+ level = "结构完整" if score >= 75 else "部分完整" if score >= 50 else "结构薄弱"
604
+ return {
605
+ "score": max(0, min(100, score)),
606
+ "score_type": "structure_rule_score",
607
+ "label": "结构准备度(规则分)",
608
+ "level": level,
609
+ "not_market_fit": True,
610
+ "dimensions": dimensions,
611
+ "metric_ratio": metric_ratio,
612
+ "guidance": "该分数只反映章节、量化证据、文本清洁度和可选的 JD 关键词覆盖,不代表招聘竞争力;不得改写为其他数值。",
613
+ }
614
+
615
+
616
+ def audit_resume(markdown, jd="", source_manifest=None, parse_warnings=None):
617
+ """Analyze a resume and return an auditable JSON-safe diagnostic report."""
618
+ model = parse_markdown_resume(markdown)
619
+ bullets = list(_bullet_texts(model))
620
+ metric_count = sum(1 for _, _, bullet in bullets if _has_metric(bullet))
621
+ sections = {
622
+ _SECTION_ALIASES.get(section.get("title"), section.get("title"))
623
+ for section in model.get("sections", [])
624
+ }
625
+ sections.discard(None)
626
+ manifest = dict(source_manifest or {
627
+ "type": "text",
628
+ "filename": "inline",
629
+ "backend": "python",
630
+ "pages": None,
631
+ "images": 0,
632
+ "text_chars": len(markdown),
633
+ "sha256": None,
634
+ "warnings": [],
635
+ })
636
+ warnings = list(parse_warnings or manifest.get("warnings") or [])
637
+ if int(manifest.get("images") or 0) > 0 and not any("图片" in item for item in warnings):
638
+ warnings.append(
639
+ "输入文件含 {} 张图片,未执行 OCR;图片内文字不会进入分析。".format(
640
+ manifest.get("images")
641
+ )
642
+ )
643
+ manifest["warnings"] = warnings
644
+ issues = _build_issues(
645
+ model,
646
+ bullets,
647
+ bool(jd),
648
+ text=markdown,
649
+ source_manifest=manifest,
650
+ )
651
+ jd_match = _jd_match(markdown, jd)
652
+ readiness = _build_structure_check(
653
+ sections,
654
+ len(bullets),
655
+ metric_count,
656
+ issues,
657
+ jd_match,
658
+ )
659
+ unknowns = []
660
+ if not jd:
661
+ unknowns.append("未提供目标 JD,无法判断岗位关键词匹配和岗位适配度。")
662
+ if int(manifest.get("images") or 0) > 0:
663
+ unknowns.append("输入文件包含图片,未执行 OCR;图片内的信息未进入分析。")
664
+ unknowns.append("规则引擎无法判断招聘竞争力、面试通过率或 Offer 结果,需人工复核。")
665
+
666
+ return {
667
+ "schema_version": SCHEMA_VERSION,
668
+ "source_manifest": manifest,
669
+ "parse_warnings": warnings,
670
+ "sections": sorted(sections),
671
+ "stats": {
672
+ "bullet_count": len(bullets),
673
+ "metric_bullets": metric_count,
674
+ "metric_ratio": readiness["metric_ratio"],
675
+ "issue_count": len(issues),
676
+ },
677
+ "issues": issues,
678
+ "questions": _build_questions(issues, jd),
679
+ "suggestions": _build_suggestions(issues, jd_match),
680
+ "jd_match": jd_match,
681
+ "readiness": readiness,
682
+ "unknowns": unknowns,
683
+ "disclaimer": "分析仅识别结构、证据与岗位匹配度,不承诺 ATS、面试或 Offer 结果,也不替代人工判断。",
684
+ }
685
+
686
+
687
+ def render_audit_markdown(report):
688
+ lines = ["# 元简简历分析", ""]
689
+ readiness = report.get("readiness", {})
690
+ manifest = report.get("source_manifest", {})
691
+ lines.append("## 输入与解析")
692
+ lines.append("- 类型:{}".format(manifest.get("type", "unknown")))
693
+ if manifest.get("filename"):
694
+ lines.append("- 文件:{}".format(manifest.get("filename")))
695
+ if manifest.get("backend"):
696
+ lines.append("- 解析后端:{}".format(manifest.get("backend")))
697
+ if manifest.get("pages") is not None:
698
+ lines.append("- 页数:{}".format(manifest.get("pages")))
699
+ lines.append("- 图片:{}".format(manifest.get("images", 0)))
700
+ if manifest.get("text_chars") is not None:
701
+ lines.append("- 文本字符:{}".format(manifest.get("text_chars")))
702
+ if manifest.get("sha256"):
703
+ lines.append("- SHA-256:`{}`".format(manifest.get("sha256")))
704
+ for warning in report.get("parse_warnings", []):
705
+ lines.append("- 解析提示:{}".format(warning))
706
+ lines.append("")
707
+
708
+ lines.append("## 总览")
709
+ lines.append("- {}:{} / 100({})".format(
710
+ readiness.get("label", "结构准备度(规则分)"),
711
+ readiness.get("score", 0),
712
+ readiness.get("level", "未知"),
713
+ ))
714
+ lines.append("- 评分类型:{};不代表招聘竞争力。".format(
715
+ readiness.get("score_type", "structure_rule_score")
716
+ ))
717
+ stats = report.get("stats", {})
718
+ lines.append("- 经历要点:{} 条;其中含指标:{} 条({}%)。".format(
719
+ stats.get("bullet_count", 0),
720
+ stats.get("metric_bullets", 0),
721
+ stats.get("metric_ratio", 0),
722
+ ))
723
+ jd_match = report.get("jd_match", {})
724
+ if jd_match.get("status") == "not_provided" or jd_match.get("coverage") is None:
725
+ lines.append("- JD 匹配:未提供 JD,不能判断岗位匹配。")
726
+ else:
727
+ lines.append("- JD 关键词覆盖:{}%。".format(jd_match.get("coverage")))
728
+ for dimension in readiness.get("dimensions", []):
729
+ score = "未知" if dimension.get("score") is None else "{} / 100".format(dimension.get("score"))
730
+ lines.append("- {}:{};{}".format(
731
+ dimension.get("label", dimension.get("key", "维度")),
732
+ score,
733
+ dimension.get("evidence", ""),
734
+ ))
735
+ lines.append("")
736
+
737
+ lines.append("## 工具发现")
738
+ if report.get("issues"):
739
+ for issue in report.get("issues", []):
740
+ lines.append("- **[{}][{}][{}]** {}:{}".format(
741
+ issue.get("id", ""),
742
+ issue.get("severity", "medium"),
743
+ issue.get("source_type", "rule"),
744
+ issue.get("code", ""),
745
+ issue.get("original", ""),
746
+ ))
747
+ lines.append(" - {}".format(issue.get("reason", "")))
748
+ else:
749
+ lines.append("- 未发现当前规则可确定的问题。")
750
+ lines.append("")
751
+
752
+ lines.append("## 高价值追问")
753
+ for index, item in enumerate(report.get("questions", []), 1):
754
+ lines.append("{}. {}".format(index, item.get("question", "")))
755
+ lines.append("")
756
+
757
+ lines.append("## 修改建议")
758
+ for item in report.get("suggestions", []):
759
+ lines.append("- **[{}]** {}".format(item.get("priority", "medium"), item.get("suggestion", "")))
760
+ if item.get("finding_id"):
761
+ lines.append(" - 关联:{}".format(item.get("finding_id")))
762
+ lines.append(" - 原文:{}".format(item.get("original", "")))
763
+ lines.append("")
764
+
765
+ lines.append("## 无法判断 / 待确认")
766
+ for item in report.get("unknowns", []):
767
+ lines.append("- {}".format(item))
768
+ pending = [
769
+ issue for issue in report.get("issues", []) if issue.get("needs_confirmation")
770
+ ]
771
+ for issue in pending:
772
+ lines.append("- {} 需用户确认:{}".format(issue.get("id", ""), issue.get("reason", "")))
773
+ if not report.get("unknowns") and not pending:
774
+ lines.append("- 未记录额外未知项。")
775
+ lines.append("")
776
+
777
+ lines.append("## 输出口径")
778
+ lines.append(
779
+ "- 只能原样引用工具返回的「结构准备度(规则分)」;不得改写为其他数值、"
780
+ "“招聘方分数”或主观数字区间。主观判断只能定性表达并列出证据。"
781
+ )
782
+ lines.append(
783
+ "- 报告必须区分工具规则发现、智能体复核发现和待用户确认事实;"
784
+ "智能体补充的发现不得冒充工具输出。"
785
+ )
786
+ lines.append("")
787
+
788
+ lines.append("## 边界")
789
+ lines.append(report.get("disclaimer", ""))
790
+ return "\n".join(lines)
791
+
792
+
793
+ def _xml_escape(text):
794
+ return html.escape(str(text), quote=True)
795
+
796
+
797
+ def render_resume_html(model):
798
+ name = html.escape(model.get("name", ""))
799
+ headline = html.escape(model.get("headline", ""))
800
+ contact = [html.escape(item) for item in model.get("contact", [])]
801
+ summary = html.escape(model.get("summary", ""))
802
+ parts = [
803
+ "<!doctype html>",
804
+ '<html lang="zh-CN">',
805
+ "<head>",
806
+ '<meta charset="utf-8">',
807
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
808
+ "<title>Resume</title>",
809
+ """<style>
810
+ :root { color-scheme: light; }
811
+ body { font-family: "Microsoft YaHei", "Noto Sans SC", Arial, sans-serif; color: #17212b; line-height: 1.55; margin: 40px auto; max-width: 800px; }
812
+ h1 { font-size: 30px; margin-bottom: 4px; }
813
+ h2 { border-bottom: 1px solid #cfd8dc; font-size: 20px; margin-top: 28px; padding-bottom: 4px; }
814
+ h3 { font-size: 16px; margin-bottom: 4px; }
815
+ .contact { color: #54616e; margin-top: 0; }
816
+ ul { margin-top: 4px; padding-left: 20px; }
817
+ @media print { body { margin: 18mm; max-width: none; } }
818
+ </style>""",
819
+ "</head>",
820
+ "<body>",
821
+ "<header>",
822
+ "<h1>{}</h1>".format(name),
823
+ ]
824
+ if headline:
825
+ parts.append('<div class="headline">{}</div>'.format(headline))
826
+ if contact:
827
+ parts.append('<p class="contact">{}</p>'.format(" | ".join(contact)))
828
+ parts.append("</header>")
829
+ if summary:
830
+ parts.append("<h2>个人简介</h2><p>{}</p>".format(summary))
831
+ for section in model.get("sections", []):
832
+ parts.append("<h2>{}</h2>".format(html.escape(section.get("title", ""))))
833
+ for item in section.get("items", []):
834
+ if item.get("heading"):
835
+ parts.append("<h3>{}</h3>".format(html.escape(item["heading"])))
836
+ bullets = item.get("bullets", [])
837
+ if bullets:
838
+ parts.append("<ul>")
839
+ for bullet in bullets:
840
+ parts.append("<li>{}</li>".format(html.escape(bullet)))
841
+ parts.append("</ul>")
842
+ parts.append("</body></html>")
843
+ return "\n".join(parts)
844
+
845
+
846
+ def export_html(model, output_path):
847
+ output = Path(output_path)
848
+ output.parent.mkdir(parents=True, exist_ok=True)
849
+ with output.open("w", encoding="utf-8", newline="\n") as handle:
850
+ handle.write(render_resume_html(model))
851
+ return output
852
+
853
+
854
+ _CONTENT_TYPES = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
855
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
856
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
857
+ <Default Extension="xml" ContentType="application/xml"/>
858
+ <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
859
+ <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
860
+ </Types>"""
861
+
862
+ _ROOT_RELS = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
863
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
864
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
865
+ </Relationships>"""
866
+
867
+ _DOC_RELS = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
868
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
869
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
870
+ </Relationships>"""
871
+
872
+ _STYLES = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
873
+ <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
874
+ <w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:pPr><w:spacing w:after="80"/></w:pPr><w:rPr><w:rFonts w:eastAsia="Microsoft YaHei"/><w:sz w:val="36"/><w:b/></w:rPr></w:style>
875
+ <w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:pPr><w:spacing w:before="220" w:after="80"/><w:outlineLvl w:val="1"/></w:pPr><w:rPr><w:rFonts w:eastAsia="Microsoft YaHei"/><w:sz w:val="28"/><w:b/></w:rPr></w:style>
876
+ <w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:pPr><w:spacing w:before="120" w:after="40"/><w:outlineLvl w:val="2"/></w:pPr><w:rPr><w:rFonts w:eastAsia="Microsoft YaHei"/><w:sz w:val="23"/><w:b/></w:rPr></w:style>
877
+ <w:style w:type="paragraph" w:styleId="BodyText"><w:name w:val="Body Text"/><w:pPr><w:spacing w:after="80"/><w:ind w:left="240"/></w:pPr><w:rPr><w:rFonts w:eastAsia="Microsoft YaHei"/><w:sz w:val="21"/></w:rPr></w:style>
878
+ </w:styles>"""
879
+
880
+
881
+ def _docx_paragraph(text, style="BodyText"):
882
+ return (
883
+ '<w:p><w:pPr><w:pStyle w:val="{}"/></w:pPr>'
884
+ '<w:r><w:t xml:space="preserve">{}</w:t></w:r></w:p>'
885
+ ).format(style, _xml_escape(text))
886
+
887
+
888
+ def _docx_body(model):
889
+ paragraphs = [_docx_paragraph(model.get("name", ""), "Title")]
890
+ if model.get("headline"):
891
+ paragraphs.append(_docx_paragraph(model["headline"], "BodyText"))
892
+ if model.get("contact"):
893
+ paragraphs.append(_docx_paragraph(" | ".join(model["contact"]), "BodyText"))
894
+ if model.get("summary"):
895
+ paragraphs.append(_docx_paragraph("个人简介", "Heading2"))
896
+ paragraphs.append(_docx_paragraph(model["summary"], "BodyText"))
897
+ for section in model.get("sections", []):
898
+ paragraphs.append(_docx_paragraph(section.get("title", ""), "Heading2"))
899
+ for item in section.get("items", []):
900
+ if item.get("heading"):
901
+ paragraphs.append(_docx_paragraph(item["heading"], "Heading3"))
902
+ for bullet in item.get("bullets", []):
903
+ paragraphs.append(_docx_paragraph("• " + bullet, "BodyText"))
904
+ return "".join(paragraphs)
905
+
906
+
907
+ def export_docx(model, output_path):
908
+ """Create a minimal but valid WordprocessingML DOCX package."""
909
+ output = Path(output_path)
910
+ output.parent.mkdir(parents=True, exist_ok=True)
911
+ document = (
912
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
913
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
914
+ "<w:body>{}<w:sectPr>"
915
+ '<w:pgSz w:w="11906" w:h="16838"/>'
916
+ '<w:pgMar w:top="1134" w:right="1134" w:bottom="1134" w:left="1134"/>'
917
+ "</w:sectPr></w:body></w:document>"
918
+ ).format(_docx_body(model))
919
+
920
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as package:
921
+ package.writestr("[Content_Types].xml", _CONTENT_TYPES)
922
+ package.writestr("_rels/.rels", _ROOT_RELS)
923
+ package.writestr("word/document.xml", document)
924
+ package.writestr("word/_rels/document.xml.rels", _DOC_RELS)
925
+ package.writestr("word/styles.xml", _STYLES)
926
+ return output
927
+
928
+
929
+ def _extract_docx_text(source):
930
+ try:
931
+ with zipfile.ZipFile(source) as package:
932
+ root = ElementTree.fromstring(package.read("word/document.xml"))
933
+ except (OSError, KeyError, zipfile.BadZipFile, ElementTree.ParseError) as error:
934
+ raise ResumeInputError("DOCX 解析失败:{}".format(error)) from error
935
+ namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
936
+ return "\n".join(
937
+ "".join(node.text or "" for node in paragraph.iter(namespace + "t")).strip()
938
+ for paragraph in root.iter(namespace + "p")
939
+ )
940
+
941
+
942
+ def _read_pdf_document(source):
943
+ try:
944
+ import pymupdf as pdf_backend
945
+ backend_name = "PyMuPDF"
946
+ except ImportError:
947
+ try:
948
+ import fitz as pdf_backend
949
+ backend_name = "PyMuPDF(fitz)"
950
+ except ImportError as error:
951
+ raise ResumeInputError(
952
+ "PDF 解析需要本地 PyMuPDF。请执行 `pip install pymupdf`,"
953
+ "或先把 PDF 转成 Markdown / DOCX 文本。"
954
+ ) from error
955
+
956
+ document = None
957
+ try:
958
+ document = pdf_backend.open(str(source))
959
+ if getattr(document, "needs_pass", False):
960
+ raise ResumeInputError("PDF 已加密,无法读取;请先导出无密码版本。")
961
+ page_texts = [page.get_text() for page in document]
962
+ images = sum(len(page.get_images(full=True)) for page in document)
963
+ except ResumeInputError:
964
+ raise
965
+ except Exception as error:
966
+ raise ResumeInputError("PDF 解析失败:{}".format(error)) from error
967
+ finally:
968
+ if document is not None:
969
+ document.close()
970
+
971
+ raw_text = "\n\n".join(page_texts).strip()
972
+ if len(raw_text) < 20:
973
+ raise ResumeInputError(
974
+ "PDF 可解析文字过少,可能是扫描件;请粘贴文字或先进行本地 OCR。"
975
+ )
976
+ backend_version = getattr(pdf_backend, "__version__", "unknown")
977
+ warnings = []
978
+ if images:
979
+ warnings.append(
980
+ "PDF 含 {} 张图片,未执行 OCR;图片内文字不会进入分析。".format(images)
981
+ )
982
+ manifest = {
983
+ "type": "pdf",
984
+ "filename": source.name,
985
+ "backend": "{} {}".format(backend_name, backend_version),
986
+ "pages": len(page_texts),
987
+ "images": images,
988
+ "text_chars": len(raw_text),
989
+ "sha256": _sha256_file(source),
990
+ "extraction_status": "text_extracted",
991
+ "warnings": warnings,
992
+ }
993
+ return {"text": _normalise_plain_resume(raw_text), "manifest": manifest}
994
+
995
+
996
+ def read_resume_document(path):
997
+ """Read Markdown, text, DOCX, or PDF with an explicit source manifest."""
998
+ source = Path(path)
999
+ if not source.is_file():
1000
+ raise FileNotFoundError("简历文件不存在:{}".format(source))
1001
+ suffix = source.suffix.lower()
1002
+ if suffix == ".pdf":
1003
+ return _read_pdf_document(source)
1004
+ if suffix == ".docx":
1005
+ raw_text = _extract_docx_text(source)
1006
+ return {
1007
+ "text": _normalise_plain_resume(raw_text),
1008
+ "manifest": {
1009
+ "type": "docx",
1010
+ "filename": source.name,
1011
+ "backend": "WordprocessingML",
1012
+ "pages": None,
1013
+ "images": None,
1014
+ "text_chars": len(raw_text),
1015
+ "sha256": _sha256_file(source),
1016
+ "extraction_status": "text_extracted",
1017
+ "warnings": ["DOCX 仅提取正文文字,复杂文本框和图片内文字可能丢失。"],
1018
+ },
1019
+ }
1020
+ if suffix == ".doc":
1021
+ raise ResumeInputError("暂不支持旧版 .doc;请另存为 .docx、PDF 或 Markdown。")
1022
+ try:
1023
+ raw_text = source.read_text(encoding="utf-8")
1024
+ except UnicodeDecodeError as error:
1025
+ raise ResumeInputError("文本输入必须为 UTF-8;无法解码该文件。") from error
1026
+ return {
1027
+ "text": raw_text,
1028
+ "manifest": {
1029
+ "type": "markdown" if suffix in (".md", ".markdown") else "text",
1030
+ "filename": source.name,
1031
+ "backend": "utf-8",
1032
+ "pages": None,
1033
+ "images": 0,
1034
+ "text_chars": len(raw_text),
1035
+ "sha256": _sha256_file(source),
1036
+ "extraction_status": "text_loaded",
1037
+ "warnings": [],
1038
+ },
1039
+ }
1040
+
1041
+
1042
+ def extract_text(path):
1043
+ """Extract normalized text from a supported resume input."""
1044
+ return read_resume_document(path)["text"]
1045
+
1046
+
1047
+ def find_pdf_browser():
1048
+ """Find a local Chromium-compatible browser suitable for headless PDF export."""
1049
+ candidates = [
1050
+ Path(r"C:\Program Files\Microsoft\Edge\Application\msedge.exe"),
1051
+ Path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"),
1052
+ Path(r"C:\Program Files\Google\Chrome\Application\chrome.exe"),
1053
+ Path(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"),
1054
+ Path.home() / r"AppData\Local\Google\Chrome\Application\chrome.exe",
1055
+ Path("/usr/bin/chromium"),
1056
+ Path("/usr/bin/chromium-browser"),
1057
+ Path("/usr/bin/google-chrome"),
1058
+ ]
1059
+ for candidate in candidates:
1060
+ if candidate.is_file():
1061
+ return str(candidate)
1062
+
1063
+ for command in ("msedge", "chrome", "chromium", "google-chrome"):
1064
+ found = shutil.which(command)
1065
+ if found:
1066
+ return found
1067
+ return None
1068
+
1069
+
1070
+ def export_pdf(model, output_path, browser_path=None):
1071
+ """Render the resume to PDF with a local Chromium-compatible browser."""
1072
+ browser = browser_path or find_pdf_browser()
1073
+ if not browser:
1074
+ raise RuntimeError("未找到本机 Chromium/Edge/Chrome,无法导出 PDF;请安装浏览器或改用 DOCX/HTML。")
1075
+ output = Path(output_path).resolve()
1076
+ output.parent.mkdir(parents=True, exist_ok=True)
1077
+ with tempfile.TemporaryDirectory(prefix="yotta-resume-") as tmp:
1078
+ page = Path(tmp) / "resume.html"
1079
+ export_html(model, page)
1080
+ command = [
1081
+ browser,
1082
+ "--headless=new",
1083
+ "--disable-gpu",
1084
+ "--no-first-run",
1085
+ "--disable-extensions",
1086
+ "--print-to-pdf=" + str(output),
1087
+ page.as_uri(),
1088
+ ]
1089
+ completed = subprocess.run(
1090
+ command,
1091
+ stdout=subprocess.PIPE,
1092
+ stderr=subprocess.PIPE,
1093
+ timeout=90,
1094
+ check=False,
1095
+ )
1096
+ if completed.returncode != 0 or not output.is_file() or not output.read_bytes().startswith(b"%PDF"):
1097
+ detail = completed.stderr.decode("utf-8", errors="replace").strip()
1098
+ raise RuntimeError("PDF 导出失败(浏览器返回 {}):{}".format(completed.returncode, detail or "未生成有效 PDF"))
1099
+ return output
1100
+
1101
+
1102
+ def cmd_audit(args):
1103
+ try:
1104
+ document = read_resume_document(args.resume)
1105
+ jd = read_resume_document(args.jd)["text"] if args.jd else ""
1106
+ except FileNotFoundError as error:
1107
+ print(str(error), file=sys.stderr)
1108
+ return 3
1109
+ except ResumeInputError as error:
1110
+ print(str(error), file=sys.stderr)
1111
+ return error.exit_code
1112
+
1113
+ report = audit_resume(
1114
+ document["text"],
1115
+ jd,
1116
+ source_manifest=document["manifest"],
1117
+ )
1118
+ if args.format == "json":
1119
+ print(json.dumps(report, ensure_ascii=False, indent=2))
1120
+ else:
1121
+ print(render_audit_markdown(report))
1122
+ return 0
1123
+
1124
+
1125
+ def cmd_export(args):
1126
+ try:
1127
+ document = read_resume_document(args.input)
1128
+ except FileNotFoundError as error:
1129
+ print(str(error), file=sys.stderr)
1130
+ return 3
1131
+ except ResumeInputError as error:
1132
+ print(str(error), file=sys.stderr)
1133
+ return error.exit_code
1134
+
1135
+ model = parse_markdown_resume(document["text"])
1136
+ outputs = []
1137
+ if args.docx:
1138
+ export_docx(model, args.docx)
1139
+ outputs.append("DOCX")
1140
+ if args.html:
1141
+ export_html(model, args.html)
1142
+ outputs.append("HTML")
1143
+ if args.pdf:
1144
+ try:
1145
+ export_pdf(model, args.pdf)
1146
+ outputs.append("PDF")
1147
+ except RuntimeError as error:
1148
+ print(str(error), file=sys.stderr)
1149
+ return 4
1150
+ if not outputs:
1151
+ print("未指定输出文件:请至少提供 --docx、--html 或 --pdf。", file=sys.stderr)
1152
+ return 2
1153
+ print("已导出:" + "、".join(outputs))
1154
+ return 0
1155
+
1156
+
1157
+ def cmd_contracts(args):
1158
+ report = validate_contracts(args.root, args.today)
1159
+ if args.format == "json":
1160
+ print(json.dumps(report, ensure_ascii=False, indent=2))
1161
+ else:
1162
+ print("元简数据契约:{}".format("PASS" if report["ok"] else "FAIL"))
1163
+ print(
1164
+ "文件 {checked_files} / 岗位族 {role_family_count} / "
1165
+ "职级 {level_count} / 题目 {question_count} / 来源 {source_count}".format(
1166
+ **report
1167
+ )
1168
+ )
1169
+ for item in report["errors"]:
1170
+ print("- [{}] {}: {}".format(
1171
+ item["code"],
1172
+ item["path"],
1173
+ item["message"],
1174
+ ))
1175
+ return 0 if report["ok"] else 6
1176
+
1177
+
1178
+ def build_parser():
1179
+ parser = argparse.ArgumentParser(
1180
+ prog="yotta-resume",
1181
+ description="元简 — 本地求职者简历分析与成品导出技能:分析简历结构、证据、岗位匹配和风险,向用户追问缺失事实,给出逐条合理化修改建议,并把确认后的内容导出为 DOCX/PDF。边界:不编造经历,不承诺 ATS、面试或 Offer 结果;不自动投递;默认本地处理且不联网。",
1182
+ )
1183
+ sub = parser.add_subparsers(dest="command")
1184
+
1185
+ audit = sub.add_parser("audit", help="分析简历并输出追问与建议")
1186
+ audit.add_argument("--resume", required=True, help="简历 Markdown、文本、DOCX 或 PDF 文件")
1187
+ audit.add_argument("--jd", help="目标岗位 JD 文本文件")
1188
+ audit.add_argument("--format", choices=("json", "markdown"), default="markdown", help="输出格式")
1189
+ audit.set_defaults(func=cmd_audit)
1190
+
1191
+ export = sub.add_parser("export", help="把确认后的简历导出为成品")
1192
+ export.add_argument("--input", required=True, help="简历 Markdown、文本、DOCX 或 PDF 文件")
1193
+ export.add_argument("--docx", help="输出 DOCX 文件")
1194
+ export.add_argument("--html", help="输出 HTML 文件")
1195
+ export.add_argument("--pdf", help="输出 PDF 文件")
1196
+ export.set_defaults(func=cmd_export)
1197
+
1198
+ contracts = sub.add_parser("contracts", help="离线校验岗位族、题库、来源与双角色契约")
1199
+ contracts.add_argument("--root", help="data 目录或技能根目录;默认使用随包 data")
1200
+ contracts.add_argument("--format", choices=("json", "text"), default="json")
1201
+ contracts.add_argument("--today", help="覆盖校验日期(YYYY-MM-DD),用于测试与回放")
1202
+ contracts.set_defaults(func=cmd_contracts)
1203
+ return parser
1204
+
1205
+
1206
+ def main(argv=None):
1207
+ args = list(sys.argv[1:] if argv is None else argv)
1208
+ if args in (["--version"], ["-V"]):
1209
+ print("yotta-resume {}".format(VERSION))
1210
+ return 0
1211
+ parser = build_parser()
1212
+ parsed = parser.parse_args(args)
1213
+ if not getattr(parsed, "func", None):
1214
+ parser.print_help()
1215
+ return 0
1216
+ return parsed.func(parsed)
1217
+
1218
+
1219
+ if __name__ == "__main__":
1220
+ sys.exit(main())