Spaces:
Sleeping
Sleeping
File size: 9,514 Bytes
61fd574 | 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 | import json
import os
import logging
import httpx
from app import database
logger = logging.getLogger(__name__)
_985_UNIVERSITIES = {
"清华大学","北京大学","复旦大学","上海交通大学","浙江大学","南京大学","中国科学技术大学",
"哈尔滨工业大学","西安交通大学","武汉大学","华中科技大学","中山大学","四川大学","南开大学",
"天津大学","山东大学","东南大学","吉林大学","厦门大学","同济大学","北京师范大学",
"国防科技大学","中国人民大学","北京航空航天大学","北京理工大学","中国农业大学",
"中央民族大学","华东师范大学","兰州大学","西北工业大学","电子科技大学",
"重庆大学","湖南大学","中南大学","大连理工大学","东北大学","华南理工大学"
}
_211_UNIVERSITIES = _985_UNIVERSITIES | {
"北京科技大学","北京交通大学","北京邮电大学","北京林业大学","北京外国语大学",
"中国传媒大学","中央财经大学","对外经济贸易大学","北京体育大学","中国政法大学",
"华北电力大学","河北工业大学","太原理工大学","内蒙古大学","辽宁大学","大连海事大学",
"延边大学","东北师范大学","哈尔滨工程大学","东北农业大学","华东理工大学","东华大学",
"上海外国语大学","上海财经大学","上海大学","苏州大学","南京航空航天大学","南京理工大学",
"中国矿业大学","河海大学","江南大学","南京农业大学","中国药科大学","南京师范大学",
"安徽大学","合肥工业大学","福州大学","南昌大学","中国石油大学","郑州大学",
"中国地质大学","武汉理工大学","华中农业大学","华中师范大学","中南财经政法大学",
"湖南师范大学","暨南大学","华南师范大学","广西大学","海南大学","西南交通大学",
"西南大学","西南财经大学","贵州大学","云南大学","西藏大学","西北大学",
"西安电子科技大学","长安大学","陕西师范大学","青海大学","宁夏大学","石河子大学",
"新疆大学","北京工业大学","天津医科大学","南京信息工程大学","南方科技大学",
"上海科技大学","中国社科院大学","中国科学院大学"
}
def _get_school_tier(school: str) -> int:
if not school:
return 0
if school in _985_UNIVERSITIES:
return 2
if school in _211_UNIVERSITIES:
return 1
return 0
def _build_resume_text(resume_data: dict) -> str:
skills = " ".join(s.lower().strip() for s in resume_data.get("skills", []))
projects = " ".join(
p if isinstance(p, str) else (p.get("name", "") + " " + p.get("description", ""))
for p in resume_data.get("projects", [])
)
parts = [
resume_data.get("summary") or "",
projects,
resume_data.get("experience") or "",
resume_data.get("education") or "",
resume_data.get("major") or "",
skills,
]
return " ".join(parts)
def _calc_match_rate(resume_data: dict, job: dict, tag_score: float, edu_score: float, vec_score: float) -> float:
final_score = vec_score * 0.35 + tag_score * 0.45 + edu_score * 0.20
return round(min(final_score, 1.0), 4)
def _calc_tag_score(resume_data: dict, job: dict) -> float:
skills = [s.lower().strip() for s in resume_data.get("skills", [])]
tags = [t.lower().strip() for t in job.get("tags", [])]
if not tags:
return 0.0
matched = sum(1 for t in tags if t in skills)
return matched / len(tags)
def _calc_edu_score(resume_data: dict, job: dict) -> float:
school = (resume_data.get("school") or "")
grade = (resume_data.get("grade") or "").lower()
jd_requirements = (job.get("requirements") or "").lower()
score = 0.4
tier = _get_school_tier(school)
if tier >= 2:
score = 1.0
elif tier >= 1:
score = 0.8
elif school:
score = 0.5
if ("硕士" in grade or "博士" in grade or "研" in grade) and "硕士" in jd_requirements:
score = min(score + 0.15, 1.0)
return score
def recommend_jobs(resume_data: dict) -> list[dict]:
if not resume_data or not resume_data.get("skills"):
return []
conn = database.get_conn()
rows = conn.execute("SELECT * FROM jobs ORDER BY job_id").fetchall()
conn.close()
jobs = []
for r in rows:
embedding_raw = r["embedding"] if "embedding" in r.keys() else ""
jobs.append({
"job_id": r["job_id"],
"name": r["name"],
"company": r["company"],
"city": r["city"],
"salary": r["salary"],
"tags": json.loads(r["tags"] or "[]"),
"description": r["description"],
"requirements": r["requirements"],
"expectation_signals": json.loads(r["expectation_signals"] or "[]"),
"_embedding": json.loads(embedding_raw) if embedding_raw else None,
})
resume_text = _build_resume_text(resume_data)
resume_vec = None
try:
from app.services.embedding_service import compute_embedding, cosine_similarity
resume_vec = compute_embedding(resume_text)
except Exception as e:
logger.warning("Resume embedding failed: %s", e)
for job in jobs:
tag_score = _calc_tag_score(resume_data, job)
edu_score = _calc_edu_score(resume_data, job)
vec_raw = 0.0
if resume_vec and job["_embedding"]:
vec_raw = cosine_similarity(resume_vec, job["_embedding"])
job["_tag_score"] = tag_score
job["_edu_score"] = edu_score
job["_vec_raw"] = vec_raw
for job in jobs:
job["_vec_score"] = max(0, min((job["_vec_raw"] - 0.30) / 0.40, 1.0))
scored = []
for job in jobs:
match_rate = _calc_match_rate(
resume_data, job,
job["_tag_score"], job["_edu_score"], job["_vec_score"]
)
scored.append({
"job_id": job["job_id"],
"match_rate": match_rate,
"job": job,
})
scored.sort(key=lambda x: x["match_rate"], reverse=True)
top_n = scored
api_key = os.getenv("DEEPSEEK_API_KEY")
if api_key and top_n:
try:
job_summaries = []
for item in top_n:
j = item["job"]
job_summaries.append(
f' {j.get("job_id")}: {j.get("name")} @ {j.get("company")} | '
f'tags={j.get("tags")} | match_rate={item["match_rate"]}'
)
system_prompt = (
"你是一个岗位推荐排序专家。给定候选人的技能列表和全部候选岗位,"
"请根据岗位与候选人的匹配程度重新排序,输出最匹配的岗位ID列表(从最匹配到最不匹配)。"
"输出格式为JSON:{\"ranked_job_ids\": [1, 2, 3, ...]}"
)
user_input = {
"skills": resume_data.get("skills", []),
"candidates": "\n".join(job_summaries),
}
with httpx.Client(timeout=30.0) as client:
resp = client.post(
"https://api.deepseek.com/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": "deepseek-chat",
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": json.dumps(user_input, ensure_ascii=False)},
],
},
)
resp.raise_for_status()
body = resp.json()
content = body["choices"][0]["message"]["content"]
llm_result = json.loads(content)
ranked_ids = llm_result.get("ranked_job_ids", [])
id_to_item = {item["job"]["job_id"]: item for item in top_n}
re_ranked = []
for raw_id in ranked_ids:
if raw_id in id_to_item:
re_ranked.append(id_to_item[raw_id])
for item in top_n:
if item["job"]["job_id"] not in ranked_ids:
re_ranked.append(item)
top_n = re_ranked
except Exception as e:
logger.warning("LLM ranking failed: %s", e)
return [
{
"job_id": item["job_id"],
"match_rate": item["match_rate"],
"match_detail": {
"semantic": round(item["job"]["_vec_score"], 4),
"tags": round(item["job"]["_tag_score"], 4),
"education": round(item["job"]["_edu_score"], 4),
},
"name": item["job"].get("name", ""),
"company": item["job"].get("company", ""),
"city": item["job"].get("city", ""),
"salary": item["job"].get("salary", ""),
"tags": item["job"].get("tags", []),
"description": item["job"].get("description", ""),
"requirements": item["job"].get("requirements", ""),
"expectation_signals": item["job"].get("expectation_signals", []),
}
for item in top_n
]
|