File size: 7,148 Bytes
3268d1c
edfd3db
 
40b45d1
3268d1c
5b1cfed
edfd3db
 
5b1cfed
3268d1c
5b1cfed
 
40b45d1
3268d1c
d8d424d
3268d1c
edfd3db
 
 
40b45d1
edfd3db
40b45d1
edfd3db
 
 
 
 
3268d1c
edfd3db
 
 
 
5b1cfed
 
edfd3db
 
 
 
 
 
 
 
 
 
 
5b1cfed
 
 
 
 
3268d1c
7bc2432
 
edfd3db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40b45d1
 
3268d1c
5b1cfed
 
 
 
edfd3db
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}