skillxray-api / main.py
Tracymgprog's picture
Update main.py
edfd3db verified
Raw History Blame Contribute Delete
7.15 kB
import os
import re
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
import numpy as np
import torch
from transformers import AutoModelForTokenClassification, AutoTokenizer
tokenizer = None
model = None
device = "cpu"
MODEL_REPO = os.getenv("MODEL_REPO", "Tracymgprog/skillxray_skill_extraction")
MODEL_API_KEY = os.getenv("MODEL_API_KEY", "")
MAX_LEN = 160
STRIDE = 32
BATCH = 16
MAX_CHARS = 100_000
TAU = float(os.getenv("EXTRACTION_TAU", "0.5"))
# Common prepositions/articles to strip from span edges
EDGE_WORDS = {
"for", "in", "with", "to", "of", "on", "at", "by",
"the", "a", "an", "and", "or", "as", "from"
}
GENERIC_NOISE = {
"making", "ensure", "ensuring", "responsible", "working",
"duties", "including", "experience", "years", "daily"
}
@asynccontextmanager
async def lifespan(app: FastAPI):
global tokenizer, model, device
print(f"Loading model and tokenizer: {MODEL_REPO}...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, use_fast=True)
model = AutoModelForTokenClassification.from_pretrained(MODEL_REPO)
model.eval()
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)
print(f"Model loaded successfully on {device}!")
yield
app = FastAPI(title="SkillXray Extraction API", lifespan=lifespan)
security = HTTPBearer()
@app.get("/")
def read_root():
return {
"status": "online",
"message": "SkillXray Extraction API is running.",
}
def snap_to_word_boundaries(text: str, start: int, end: int) -> tuple[int, int]:
"""Expand character indices outward to whitespace boundaries."""
while start > 0 and not text[start - 1].isspace():
start -= 1
while end < len(text) and not text[end].isspace():
end += 1
return start, end
def clean_and_validate_span(raw_span: str) -> str | None:
"""Trim edge prepositions, punctuation, and discard noise."""
span = raw_span.strip(" \t\n\r,;:–—/&*()[]{}'\"")
# Strip edge words repeatedly
tokens = span.split()
while tokens and tokens[0].lower() in EDGE_WORDS:
tokens.pop(0)
while tokens and tokens[-1].lower() in EDGE_WORDS:
tokens.pop()
cleaned = " ".join(tokens).strip(" \t\n\r,;:–—/&*()[]{}'\"")
# Validation filters
if len(cleaned) < 2:
return None
if cleaned.lower() in EDGE_WORDS or cleaned.lower() in GENERIC_NOISE:
return None
# Must contain at least one alphanumeric character
if not any(c.isalnum() for c in cleaned):
return None
# Reject strings that are more than 70% punctuation or symbols
letters = sum(c.isalnum() for c in cleaned)
if letters / len(cleaned) < 0.5:
return None
# Reject overly long run-on sentences (duties, not skills)
if len(cleaned.split()) > 8:
return None
return cleaned
def extract_spans_from_window(text: str, enc, window_idx: int, probs: np.ndarray, tau: float) -> list[str]:
"""Decodes token probabilities by grouping at the word-token level."""
offsets = enc["offset_mapping"][window_idx].tolist()
word_ids = enc.word_ids(batch_index=window_idx)
# 1. Group subwords into whole words
words = {}
word_order = []
for t_idx, w_idx in enumerate(word_ids):
if w_idx is None:
continue
s, e = offsets[t_idx]
if e <= s:
continue
if w_idx not in words:
words[w_idx] = [s, e, t_idx]
word_order.append(w_idx)
else:
words[w_idx][1] = max(words[w_idx][1], e)
if not word_order:
return []
# Model label IDs: O is 0, B-SKILL is 1, I-SKILL is 2
o_id = model.config.label2id.get("O", 0)
b_id = model.config.label2id.get("B-SKILL", 1)
i_id = model.config.label2id.get("I-SKILL", 2)
# 2. Extract sequences where P(skill) >= tau
extracted = []
current_span = None
for w_idx in word_order:
s, e, t_idx = words[w_idx]
p = probs[t_idx]
p_skill = 1.0 - float(p[o_id])
is_begin = bool(p[b_id] >= p[i_id])
if p_skill >= tau:
if current_span is None or is_begin:
if current_span is not None:
extracted.append(current_span)
current_span = {"start": s, "end": e}
else:
current_span["end"] = e
else:
if current_span is not None:
extracted.append(current_span)
current_span = None
if current_span is not None:
extracted.append(current_span)
# 3. Snap to full word boundaries and clean
valid_skills = []
for sp in extracted:
snapped_s, snapped_e = snap_to_word_boundaries(text, sp["start"], sp["end"])
candidate = text[snapped_s:snapped_e]
cleaned = clean_and_validate_span(candidate)
if cleaned:
valid_skills.append(cleaned)
return valid_skills
def extract_from_text(text: str) -> list[str]:
cleaned_input = re.sub(r"[\r\n]+", "\n", text).strip()
if not cleaned_input:
return []
enc = tokenizer(
cleaned_input,
truncation=True,
max_length=MAX_LEN,
stride=STRIDE,
return_overflowing_tokens=True,
return_offsets_mapping=True,
padding="max_length",
return_tensors="pt",
)
enc.pop("overflow_to_sample_mapping", None)
num_windows = enc["input_ids"].shape[0]
all_skills = []
for i in range(0, num_windows, BATCH):
batch = {
"input_ids": enc["input_ids"][i:i + BATCH].to(device),
"attention_mask": enc["attention_mask"][i:i + BATCH].to(device)
}
with torch.no_grad():
logits = model(**batch).logits
probs = torch.softmax(logits, dim=-1).cpu().numpy()
for w in range(probs.shape[0]):
window_skills = extract_spans_from_window(
cleaned_input, enc, i + w, probs[w], TAU
)
all_skills.extend(window_skills)
# Preserve order and eliminate case-insensitive duplicates
unique_skills = []
seen = set()
for s in all_skills:
key = s.casefold()
if key not in seen:
seen.add(key)
unique_skills.append(s)
return unique_skills
@app.post("/api/v1/extract-skills")
async def extract_skills(
payload: dict,
credentials: HTTPAuthorizationCredentials = Security(security),
):
if MODEL_API_KEY and credentials.credentials != MODEL_API_KEY:
raise HTTPException(status_code=401, detail="Invalid authorization token.")
if not model or not tokenizer:
raise HTTPException(
status_code=503,
detail="Model is still initializing. Please try again in a moment.",
)
text = payload.get("text", "")
if not text:
raise HTTPException(status_code=400, detail="Text field is required.")
skills = extract_from_text(text[:MAX_CHARS])
return {"skills": skills, "count": len(skills)}