NhanSoHocCode's picture
Add Option models
2aad837 verified
Raw History Blame Contribute Delete
25.8 kB
import os
import sys
import subprocess
import html
# Tự động cài đặt transformers & accelerate nếu chưa có trên môi trường
try:
import transformers
except ImportError:
print("Installing missing dependencies: transformers, accelerate...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "transformers", "accelerate"])
import transformers
import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline
# Hỗ trợ Hugging Face ZeroGPU (nếu Space đang cấu hình phần cứng GPU)
try:
import spaces
except ImportError:
class _MockSpaces:
@staticmethod
def GPU(fn=None, *args, **kwargs):
if fn is not None:
return fn
return lambda f: f
spaces = _MockSpaces()
# 1. Quản lý danh sách mô hình & Caching Pipeline
DEFAULT_MODEL = "NhanSoHocCode/xlmr-ner-4labels-v2"
MODEL_OPTIONS = [
("✨ XLM-RoBERTa NER 4Labels v2 (Mới nhất / Khuyên dùng)", "NhanSoHocCode/xlmr-ner-4labels-v2"),
("🏷️ XLM-RoBERTa NER 4Labels v1 (Bản gốc)", "NhanSoHocCode/xlmr-ner-4labels"),
("⚙️ Tùy chỉnh (Nhập checkpoint Hugging Face khác...)", "custom")
]
PIPELINE_CACHE = {}
def get_ner_pipeline(model_id: str):
"""
Tải hoặc lấy từ cache pipeline trích xuất thực thể theo model_id.
Hỗ trợ cả checkpoint có sẵn hoặc checkpoint tùy chỉnh có cùng kiến trúc.
"""
model_id = model_id.strip() if model_id else DEFAULT_MODEL
if model_id in PIPELINE_CACHE:
return PIPELINE_CACHE[model_id], None
try:
print(f"Loading model checkpoint: {model_id} ...")
device = 0 if torch.cuda.is_available() else -1
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForTokenClassification.from_pretrained(model_id)
pipe = pipeline(
"token-classification",
model=model,
tokenizer=tokenizer,
aggregation_strategy="simple",
device=device
)
PIPELINE_CACHE[model_id] = pipe
print(f"Model loaded successfully: {model_id}")
return pipe, None
except Exception as e:
err_msg = f"Không thể tải mô hình '{model_id}'. Chi tiết lỗi: {str(e)}"
print(err_msg)
return None, err_msg
# Tải trước mô hình mặc định khi khởi động ứng dụng
print(f"Pre-loading default model: {DEFAULT_MODEL} ...")
get_ner_pipeline(DEFAULT_MODEL)
# 2. Cấu hình nhãn & biểu tượng & màu sắc
LABEL_CONFIG = {
"HARD_SKILL": {
"icon": "🛠️",
"name": "HARD_SKILL",
"color": "#ef4444", # Đỏ san hô
"bg": "#ef4444",
"text_color": "#ffffff"
},
"SOFT_SKILL": {
"icon": "🤝",
"name": "SOFT_SKILL",
"color": "#d97706", # Hổ phách / Vàng cam
"bg": "#d97706",
"text_color": "#ffffff"
},
"EDUCATION": {
"icon": "🎓",
"name": "EDUCATION",
"color": "#0284c7", # Xanh lam / Cyan
"bg": "#0284c7",
"text_color": "#ffffff"
},
"MAJOR": {
"icon": "📊",
"name": "MAJOR",
"color": "#16a34a", # Xanh lá lục bảo
"bg": "#16a34a",
"text_color": "#ffffff"
}
}
ORDERED_LABELS = ["HARD_SKILL", "SOFT_SKILL", "EDUCATION", "MAJOR"]
@spaces.GPU
def analyze_ner(title, text, threshold=0.0, model_choice="NhanSoHocCode/xlmr-ner-4labels-v2", custom_model_id=""):
# Xác định checkpoint thực tế được chọn
if model_choice == "custom":
active_model = (custom_model_id or "").strip()
if not active_model:
err_html = """
<div style="padding: 18px; text-align: center; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
⚠️ <b>Chưa nhập thông tin mô hình:</b> Vui lòng điền Hugging Face Repo ID hoặc checkpoint tùy chỉnh để tiếp tục.
</div>
"""
return err_html, "Lỗi: Bạn đã chọn mô hình tùy chỉnh nhưng chưa nhập Hugging Face Repo ID.", []
else:
active_model = model_choice.strip() if model_choice else DEFAULT_MODEL
if not text or not text.strip():
empty_msg = """
<div style="padding: 24px; text-align: center; color: #6b7280; font-family: monospace;">
Vui lòng nhập văn bản mô tả công việc (Job Description) để bắt đầu phân tích.
</div>
"""
return empty_msg, "Vui lòng nhập văn bản JD.", []
title = title.strip() if title and title.strip() else "Kết quả phân tích JD"
raw_text = text.strip()
# Lấy pipeline mô hình
ner_pipe, load_err = get_ner_pipeline(active_model)
if load_err or ner_pipe is None:
err_html = f"""
<div style="padding: 18px; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; font-family: sans-serif;">
<b>❌ Lỗi tải mô hình ({html.escape(active_model)}):</b><br/>
<span style="font-size: 13.5px;">{html.escape(load_err or 'Không thể khởi tạo mô hình.')}</span><br/><br/>
<small style="color: #6b7280;">Vui lòng kiểm tra lại tên repo trên Hugging Face hoặc đảm bảo mô hình có cùng kiến trúc Token Classification.</small>
</div>
"""
return err_html, f"Lỗi tải mô hình '{active_model}': {load_err}", []
# Thực hiện trích xuất
try:
raw_results = ner_pipe(raw_text)
except Exception as e:
err_msg = f"Lỗi trong quá trình trích xuất thực thể: {str(e)}"
err_html = f"""
<div style="padding: 18px; color: #dc2626; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px;">
<b>❌ Lỗi thực thi mô hình:</b> {html.escape(err_msg)}
</div>
"""
return err_html, err_msg, []
# Lọc theo ngưỡng tin cậy
entities = [
item for item in raw_results
if float(item["score"]) >= threshold
]
# Sắp xếp các thực thể theo thứ tự xuất hiện trong câu
entities = sorted(entities, key=lambda x: x["start"])
# Xử lý gối vị trí (nếu có chồng lấn start/end)
filtered_entities = []
last_end = -1
for ent in entities:
if ent["start"] >= last_end:
filtered_entities.append(ent)
last_end = ent["end"]
# 1. Tạo câu có đánh dấu thực thể dạng HTML màu sắc & dạng văn bản thô
rendered_parts = []
raw_parts = []
last_idx = 0
for ent in filtered_entities:
start = ent["start"]
end = ent["end"]
label = ent["entity_group"]
cfg = LABEL_CONFIG.get(label, {
"icon": "🏷️",
"color": "#6366f1",
"bg": "#6366f1",
"text_color": "#ffffff"
})
# Đoạn chữ thường phía trước
if start > last_idx:
plain_segment = raw_text[last_idx:start]
rendered_parts.append(html.escape(plain_segment))
raw_parts.append(plain_segment)
# Lấy từ thực tế trong chuỗi gốc
ent_word = raw_text[start:end]
# Thẻ màu HTML
badge_html = (
f'<span class="ner-badge" style="background-color: {cfg["bg"]}; color: {cfg["text_color"]};">'
f'[{label}: {html.escape(ent_word)}]'
f'</span>'
)
rendered_parts.append(badge_html)
raw_parts.append(f"[{label}: {ent_word}]")
last_idx = end
# Đoạn văn bản còn lại sau thực thể cuối cùng
if last_idx < len(raw_text):
plain_segment = raw_text[last_idx:]
rendered_parts.append(html.escape(plain_segment))
raw_parts.append(plain_segment)
tagged_html = "".join(rendered_parts)
tagged_plain = "".join(raw_parts)
# 2. Thống kê danh sách thực thể theo nhóm
grouped = {lbl: [] for lbl in ORDERED_LABELS}
for ent in filtered_entities:
lbl = ent["entity_group"]
if lbl in grouped:
grouped[lbl].append(ent)
else:
grouped.setdefault(lbl, []).append(ent)
stats_html_lines = []
stats_plain_lines = []
table_rows = []
stt = 1
for lbl in ORDERED_LABELS:
items = grouped.get(lbl, [])
if not items:
continue
cfg = LABEL_CONFIG.get(lbl, {"icon": "🏷️", "color": "#4b5563"})
items_detail = []
for it in items:
word = it["word"]
score_pct = float(it["score"]) * 100
items_detail.append(f"{word} ({score_pct:.1f}%)")
table_rows.append([stt, f"{cfg['icon']} {lbl}", word, f"{score_pct:.1f}%", f"{it['start']}:{it['end']}"])
stt += 1
items_str = ", ".join(items_detail)
# Dòng thống kê HTML
stat_html = (
f'<div class="stat-row">'
f' <span class="stat-tag" style="color: {cfg["color"]}; font-weight: 700;">'
f' {cfg["icon"]} {lbl} ({len(items)}):'
f' </span> '
f' <span class="stat-content">{html.escape(items_str)}</span>'
f'</div>'
)
stats_html_lines.append(stat_html)
# Dòng thống kê thô
stats_plain_lines.append(f" {cfg['icon']} {lbl} ({len(items)}): {items_str}")
stats_html_content = "\n".join(stats_html_lines)
stats_plain_content = "\n".join(stats_plain_lines)
# 3. Kết xuất giao diện thẻ theo đúng hình mẫu
card_html = f"""
<div class="jd-result-card">
<div class="border-line-double">===============================================================================================</div>
<div class="jd-title">📌 {html.escape(title)}</div>
<div class="model-badge-info">🤖 Mô hình: <code>{html.escape(active_model)}</code></div>
<div class="border-line-single">-----------------------------------------------------------------------------------------------</div>
<div class="section-heading">Văn bản gốc:</div>
<div class="section-body raw-body">{html.escape(raw_text)}</div>
<div class="border-line-single">-----------------------------------------------------------------------------------------------</div>
<div class="section-heading">Kết quả trích xuất trực tiếp trong câu:</div>
<div class="section-body tagged-body">{tagged_html}</div>
<div class="border-line-single">-----------------------------------------------------------------------------------------------</div>
<div class="section-heading">Thống kê danh sách thực thể:</div>
<div class="section-body stats-body">
{stats_html_content if stats_html_content else '<div style="color: #888;">Không phát hiện thực thể nào vượt qua ngưỡng tin cậy.</div>'}
</div>
<div class="border-line-double">===============================================================================================</div>
</div>
"""
# 4. Văn bản Plain Text hoàn chỉnh (sao chép nhanh)
plain_output = f"""===============================================================================================
📌 {title}
🤖 Mô hình: {active_model}
-----------------------------------------------------------------------------------------------
Văn bản gốc:
{raw_text}
-----------------------------------------------------------------------------------------------
Kết quả trích xuất trực tiếp trong câu:
{tagged_plain}
-----------------------------------------------------------------------------------------------
Thống kê danh sách thực thể:
{stats_plain_content if stats_plain_content else ' (Không phát hiện thực thể nào)'}
==============================================================================================="""
return card_html, plain_output, table_rows
# Helper tạo link Hugging Face
def render_model_link(model_choice, custom_id):
is_custom = (model_choice == "custom")
target = (custom_id or "").strip() if is_custom else model_choice
if target and not target.startswith("http"):
hf_url = f"https://huggingface.co/{target}"
return (
f'<div class="hf-link-wrapper">'
f' <span class="hf-icon">🤗</span>'
f' <span>Checkpoint hiện tại: </span>'
f' <a href="{hf_url}" target="_blank" class="hf-link"><b>{html.escape(target)}</b> ↗</a>'
f'</div>'
)
return (
'<div class="hf-link-wrapper">'
' <span class="hf-icon">💡</span>'
' <span>Nhập Hugging Face Repo ID hoặc checkpoint cục bộ tương thích với 4 nhãn chuẩn.</span>'
'</div>'
)
def handle_model_change(choice, custom_id):
show_custom = (choice == "custom")
link_html = render_model_link(choice, custom_id)
return gr.update(visible=show_custom), link_html
def handle_custom_id_change(custom_id):
return render_model_link("custom", custom_id)
# Custom CSS cho giao diện
custom_css = """
/* Font và định dạng tổng quát */
.container {
max-width: 1050px !important;
margin: 0 auto !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
/* Khung chọn mô hình thay thế dòng chữ mô tả */
.model-selector-panel {
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 14px 18px;
margin: 10px 0 16px 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
}
.hf-link-wrapper {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: #475569;
margin-top: 6px;
padding-left: 2px;
}
.hf-link {
color: #2563eb !important;
text-decoration: none !important;
transition: color 0.15s ease;
}
.hf-link:hover {
color: #1d4ed8 !important;
text-decoration: underline !important;
}
.model-badge-info {
font-size: 13px;
color: #4b5563;
margin: 4px 0 6px 0;
}
.model-badge-info code {
background-color: #f3f4f6;
color: #1f2937;
padding: 2px 6px;
border-radius: 4px;
font-size: 12.5px;
}
/* Thẻ kết quả mô phỏng chính xác hình mẫu */
.jd-result-card {
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 20px 24px;
margin-top: 10px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
font-family: "Consolas", "Courier New", monospace, sans-serif;
color: #1f2937;
line-height: 1.8;
}
/* Dark mode compatibility */
@media (prefers-color-scheme: dark) {
.model-selector-panel {
background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
border-color: #334155;
}
.hf-link-wrapper {
color: #94a3b8;
}
.hf-link {
color: #60a5fa !important;
}
.model-badge-info {
color: #94a3b8;
}
.model-badge-info code {
background-color: #334155;
color: #f1f5f9;
}
.jd-result-card {
background-color: #1e293b;
border-color: #334155;
color: #f1f5f9;
}
.jd-result-card .section-heading {
color: #e2e8f0 !important;
}
.jd-result-card .border-line-double,
.jd-result-card .border-line-single {
color: #64748b !important;
}
}
.border-line-double {
color: #9ca3af;
font-size: 13px;
letter-spacing: 1px;
user-select: none;
overflow: hidden;
white-space: nowrap;
}
.border-line-single {
color: #d1d5db;
font-size: 13px;
margin: 10px 0;
user-select: none;
overflow: hidden;
white-space: nowrap;
}
.jd-title {
font-size: 16px;
font-weight: 700;
color: #111827;
margin: 6px 0 2px 0;
}
@media (prefers-color-scheme: dark) {
.jd-title { color: #f8fafc; }
}
.section-heading {
font-size: 14px;
font-weight: 600;
color: #374151;
margin-bottom: 6px;
}
.section-body {
font-size: 14.5px;
line-height: 1.9;
word-break: break-word;
}
.raw-body {
color: #374151;
}
@media (prefers-color-scheme: dark) {
.raw-body { color: #cbd5e1; }
}
/* Các nhãn thực thể highlight trong câu */
.ner-badge {
display: inline-block;
padding: 1px 7px;
margin: 1px 2px;
border-radius: 4px;
font-size: 13.5px;
font-weight: 600;
letter-spacing: 0.2px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
white-space: nowrap;
}
/* Phần thống kê */
.stats-body {
margin-top: 4px;
}
.stat-row {
margin-bottom: 6px;
line-height: 1.7;
}
.stat-tag {
font-size: 14px;
}
.stat-content {
font-size: 14px;
color: #374151;
}
@media (prefers-color-scheme: dark) {
.stat-content { color: #cbd5e1; }
}
/* Legend badges trên đầu trang */
.legend-pill {
display: inline-flex;
align-items: center;
padding: 4px 10px;
border-radius: 9999px;
font-size: 12.5px;
font-weight: 600;
margin-right: 8px;
margin-bottom: 6px;
color: white;
}
"""
# Khởi tạo giao diện Gradio
with gr.Blocks(title="XLM-RoBERTa NER Job Description") as demo:
gr.HTML(f"<style>{custom_css}</style>")
# Tiêu đề chính
gr.Markdown("# 🏷️ Trích xuất Kỹ năng & Thực thể từ Job Description")
# VỊ TRÍ THAY THẾ DÒNG CHỮ CŨ: KHỐI CHỨC NĂNG CHỌN MÔ HÌNH
with gr.Group(elem_classes=["model-selector-panel"]):
with gr.Row():
model_dropdown = gr.Dropdown(
label="🎯 Chọn mô hình trích xuất (Model Checkpoint)",
choices=MODEL_OPTIONS,
value=DEFAULT_MODEL,
interactive=True,
scale=5,
info="Chuyển đổi giữa 2 checkpoint v1 / v2 đã huấn luyện hoặc tùy chỉnh checkpoint mới."
)
custom_model_textbox = gr.Textbox(
label="🔗 Hugging Face Repo ID hoặc Checkpoint tùy chỉnh",
placeholder="Ví dụ: NhanSoHocCode/xlmr-ner-4labels hoặc username/model-name",
value="",
interactive=True,
visible=False,
scale=5,
info="Mô hình cần có cùng kiến trúc Token Classification và 4 nhãn thực thể chuẩn."
)
model_link_html = gr.HTML(
value=render_model_link(DEFAULT_MODEL, ""),
elem_classes=["hf-link-container"]
)
# Dải hiển thị 4 nhóm nhãn thực thể chuẩn
gr.HTML(
"""
<div style="margin-top: 4px; margin-bottom: 16px;">
<span class="legend-pill" style="background-color: #ef4444;">🛠️ HARD_SKILL: Kỹ năng chuyên môn / Công nghệ</span>
<span class="legend-pill" style="background-color: #d97706;">🤝 SOFT_SKILL: Kỹ năng mềm / Giao tiếp</span>
<span class="legend-pill" style="background-color: #0284c7;">🎓 EDUCATION: Học vị / Bằng cấp</span>
<span class="legend-pill" style="background-color: #16a34a;">📊 MAJOR: Chuyên ngành đào tạo</span>
</div>
"""
)
with gr.Row():
with gr.Column(scale=5):
title_input = gr.Textbox(
label="Tiêu đề JD (Tùy chọn)",
placeholder="Ví dụ: Mẫu JD Senior Golang / Distributed Systems",
value="Mẫu JD Senior Golang / Distributed Systems",
lines=1
)
text_input = gr.Textbox(
label="Nội dung Job Description (Văn bản gốc)",
placeholder="Nhập hoặc dán nội dung tuyển dụng vào đây...",
value=(
"Tuyển dụng Senior Backend Engineer yêu cầu tốt nghiệp Cử nhân chuyên ngành Công nghệ thông tin. "
"Có từ 4 năm kinh nghiệm làm việc với Golang, gRPC, Microservices và Event-Driven Architecture. "
"Thành thạo cơ sở dữ liệu PostgreSQL, Redis Caching và Apache Kafka. "
"Kinh nghiệm triển khai trên Kubernetes, Docker, CI/CD. "
"Sử dụng thành thạo Cursor, GitHub Copilot để tăng tốc lập trình. "
"Yêu cầu kỹ năng làm việc nhóm, tư duy giải quyết vấn đề và tiếng Anh giao tiếp tốt."
),
lines=6
)
with gr.Accordion("⚙️ Tùy chỉnh nâng cao", open=False):
threshold_slider = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.05,
label="Ngưỡng độ tin cậy tối thiểu (Confidence Threshold)",
info="Chỉ hiển thị các thực thể có độ tin cậy lớn hơn hoặc bằng giá trị này."
)
with gr.Row():
submit_btn = gr.Button("🚀 Phân tích & Trích xuất", variant="primary", size="lg")
clear_btn = gr.ClearButton([text_input, title_input], value="🧹 Xóa nội dung", size="lg")
# Các ví dụ mẫu chuẩn bị sẵn
gr.Examples(
examples=[
[
"Mẫu JD Senior Golang / Distributed Systems",
"Tuyển dụng Senior Backend Engineer yêu cầu tốt nghiệp Cử nhân chuyên ngành Công nghệ thông tin. Có từ 4 năm kinh nghiệm làm việc với Golang, gRPC, Microservices và Event-Driven Architecture. Thành thạo cơ sở dữ liệu PostgreSQL, Redis Caching và Apache Kafka. Kinh nghiệm triển khai trên Kubernetes, Docker, CI/CD. Sử dụng thành thạo Cursor, GitHub Copilot để tăng tốc lập trình. Yêu cầu kỹ năng làm việc nhóm, tư duy giải quyết vấn đề và tiếng Anh giao tiếp tốt.",
0.5,
"NhanSoHocCode/xlmr-ner-4labels-v2",
""
],
[
"Mẫu JD AI / Data Science Engineer",
"Tìm kiếm Kỹ sư AI tốt nghiệp Thạc sĩ hoặc Cử nhân ngành Khoa học Máy tính. Có kinh nghiệm với Python, PyTorch, Transformers và mô hình ngôn ngữ lớn (LLM). Thành thạo kỹ thuật RAG, Fine-tuning, triển khai mô hình với FastAPI, Docker trên GCP. Yêu cầu tư duy phản biện, kỹ năng nghiên cứu độc lập và khả năng tiếng Anh chuyên ngành xuất sắc.",
0.5,
"NhanSoHocCode/xlmr-ner-4labels-v2",
""
],
[
"Mẫu JD Frontend Lead Developer",
"Yêu cầu bằng Kỹ sư hoặc Đại học chuyên ngành Công nghệ phần mềm. Tối thiểu 5 năm kinh nghiệm với JavaScript, TypeScript, ReactJS, Next.js và TailwindCSS. Có kinh nghiệm tối ưu hiệu năng web, quản trị state với Redux Toolkit hoặc Zustand. Cần có kỹ năng lãnh đạo đội ngũ, khả năng giao tiếp và truyền đạt thông tin mạch lạc.",
0.5,
"NhanSoHocCode/xlmr-ner-4labels",
""
]
],
inputs=[title_input, text_input, threshold_slider, model_dropdown, custom_model_textbox],
label="💡 Nhấp vào các mẫu JD để thử nghiệm nhanh:"
)
with gr.Column(scale=6):
with gr.Tabs():
with gr.TabItem("🎨 Giao diện trực quan (Visual Card)"):
card_output = gr.HTML(label="Kết quả trực quan")
with gr.TabItem("📋 Văn bản thô (Plain Text)"):
raw_output = gr.Textbox(
lines=16,
max_lines=30,
label="Văn bản định dạng Console (Sao chép nhanh)"
)
with gr.TabItem("📊 Bảng dữ liệu chi tiết (Table)"):
table_output = gr.Dataframe(
headers=["STT", "Nhóm nhãn", "Thực thể", "Độ tin cậy", "Vị trí (Start:End)"],
label="Danh sách thực thể chi tiết"
)
# Sự kiện tương tác bộ chọn mô hình
model_dropdown.change(
fn=handle_model_change,
inputs=[model_dropdown, custom_model_textbox],
outputs=[custom_model_textbox, model_link_html]
)
custom_model_textbox.input(
fn=handle_custom_id_change,
inputs=[custom_model_textbox],
outputs=[model_link_html]
)
# Xử lý sự kiện click nút
common_inputs = [title_input, text_input, threshold_slider, model_dropdown, custom_model_textbox]
common_outputs = [card_output, raw_output, table_output]
submit_btn.click(
fn=analyze_ner,
inputs=common_inputs,
outputs=common_outputs
)
# Chạy lần đầu khi load trang
demo.load(
fn=analyze_ner,
inputs=common_inputs,
outputs=common_outputs
)
if __name__ == "__main__":
demo.launch()