Tracymgprog commited on
Commit
edfd3db
·
verified ·
1 Parent(s): 40b45d1

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +199 -96
main.py CHANGED
@@ -1,9 +1,11 @@
1
- from contextlib import asynccontextmanager
2
  import os
 
 
3
 
4
- import torch
5
  from fastapi import FastAPI, HTTPException, Security
6
  from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
 
 
7
  from transformers import AutoModelForTokenClassification, AutoTokenizer
8
 
9
  tokenizer = None
@@ -12,28 +14,35 @@ device = "cpu"
12
 
13
  MODEL_REPO = os.getenv("MODEL_REPO", "Tracymgprog/skillxray_skill_extraction")
14
  MODEL_API_KEY = os.getenv("MODEL_API_KEY", "")
15
-
16
- MAX_LEN = 160 # tokens per window (what the model was trained with)
17
- STRIDE = 20 # tokens shared between neighbouring windows, so skills at an edge aren't cut
18
- BATCH = 16 # windows per forward pass
19
  MAX_CHARS = 100_000
 
20
 
 
 
 
 
 
21
 
22
- @asynccontextmanager
23
- async def lifespan(app: FastAPI):
24
- global tokenizer, model, device
25
- print(f"Loading fine-tuned model and tokenizer from Hugging Face Hub: {MODEL_REPO}...")
26
-
27
- # A fast tokenizer is required for character offsets and overlapping windows.
28
- tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, use_fast=True)
29
- model = AutoModelForTokenClassification.from_pretrained(MODEL_REPO)
30
- model.eval()
31
 
32
- device = "cuda" if torch.cuda.is_available() else "cpu"
33
- model = model.to(device)
34
 
35
- print("Model and tokenizer loaded successfully!")
36
- yield
 
 
 
 
 
 
 
 
 
37
 
38
 
39
  app = FastAPI(title="SkillXray Extraction API", lifespan=lifespan)
@@ -42,68 +51,163 @@ security = HTTPBearer()
42
 
43
  @app.get("/")
44
  def read_root():
45
- return {
46
- "status": "online",
47
- "message": "SkillXray Extraction API is running. Send POST requests to /api/v1/extract-skills",
48
- }
49
-
50
-
51
- def spans_from_window(text, preds, offsets):
52
- """Turn one window's B/I predictions (1 = B-SKILL, 2 = I-SKILL) into skill strings."""
53
- found = []
54
- start_char = end_char = None
55
-
56
- def flush():
57
- nonlocal start_char, end_char
58
- if start_char is not None:
59
- skill = text[start_char:end_char].strip()
60
- if len(skill) > 1:
61
- found.append(skill)
62
- start_char = end_char = None
63
-
64
- for pred, (start, end) in zip(preds, offsets):
65
- if start == end: # special or padding token
66
- flush()
67
- continue
68
- if pred == 1: # B: a new skill begins, so close any skill in progress
69
- flush()
70
- start_char, end_char = start, end
71
- elif pred == 2: # I: continue the current skill
72
- if start_char is None:
73
- start_char = start
74
- end_char = end
75
- else:
76
- flush()
77
- flush()
78
- return found
79
-
80
-
81
- def extract_from_text(text):
82
- # Overlapping windows cover the WHOLE resume. Truncating to the first 160
83
- # tokens would only ever read the top of the first page.
84
- enc = tokenizer(
85
- text,
86
- truncation=True,
87
- max_length=MAX_LEN,
88
- stride=STRIDE,
89
- return_overflowing_tokens=True,
90
- return_offsets_mapping=True,
91
- padding="max_length",
92
- return_tensors="pt",
93
- )
94
- enc.pop("overflow_to_sample_mapping", None)
95
- offsets = enc.pop("offset_mapping")
96
-
97
- skills = []
98
- total = offsets.shape[0]
99
- for i in range(0, total, BATCH):
100
- batch = {k: v[i:i + BATCH].to(device) for k, v in enc.items()}
101
- with torch.no_grad():
102
- preds = model(**batch).logits.argmax(dim=-1).cpu().numpy()
103
- for w in range(preds.shape[0]):
104
- skills.extend(spans_from_window(text, preds[w], offsets[i + w].tolist()))
105
-
106
- return list(dict.fromkeys(skills)) # de-duplicate, keep order
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
 
109
  @app.post("/api/v1/extract-skills")
@@ -111,18 +215,17 @@ async def extract_skills(
111
  payload: dict,
112
  credentials: HTTPAuthorizationCredentials = Security(security),
113
  ):
114
- if MODEL_API_KEY and credentials.credentials != MODEL_API_KEY:
115
- raise HTTPException(status_code=401, detail="Invalid authorization token.")
116
-
117
- if not model or not tokenizer:
118
- raise HTTPException(
119
- status_code=503,
120
- detail="Model is still initializing. Please try again in a moment.",
121
- )
122
-
123
- text = payload.get("text", "")
124
- if not text:
125
- raise HTTPException(status_code=400, detail="Text field is required.")
126
-
127
- unique_skills = extract_from_text(text[:MAX_CHARS])
128
- return {"skills": unique_skills, "count": len(unique_skills)}
 
 
1
  import os
2
+ import re
3
+ from contextlib import asynccontextmanager
4
 
 
5
  from fastapi import FastAPI, HTTPException, Security
6
  from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
7
+ import numpy as np
8
+ import torch
9
  from transformers import AutoModelForTokenClassification, AutoTokenizer
10
 
11
  tokenizer = None
 
14
 
15
  MODEL_REPO = os.getenv("MODEL_REPO", "Tracymgprog/skillxray_skill_extraction")
16
  MODEL_API_KEY = os.getenv("MODEL_API_KEY", "")
17
+ MAX_LEN = 160
18
+ STRIDE = 32
19
+ BATCH = 16
 
20
  MAX_CHARS = 100_000
21
+ TAU = float(os.getenv("EXTRACTION_TAU", "0.5"))
22
 
23
+ # Common prepositions/articles to strip from span edges
24
+ EDGE_WORDS = {
25
+ "for", "in", "with", "to", "of", "on", "at", "by",
26
+ "the", "a", "an", "and", "or", "as", "from"
27
+ }
28
 
29
+ GENERIC_NOISE = {
30
+ "making", "ensure", "ensuring", "responsible", "working",
31
+ "duties", "including", "experience", "years", "daily"
32
+ }
 
 
 
 
 
33
 
 
 
34
 
35
+ @asynccontextmanager
36
+ async def lifespan(app: FastAPI):
37
+ global tokenizer, model, device
38
+ print(f"Loading model and tokenizer: {MODEL_REPO}...")
39
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, use_fast=True)
40
+ model = AutoModelForTokenClassification.from_pretrained(MODEL_REPO)
41
+ model.eval()
42
+ device = "cuda" if torch.cuda.is_available() else "cpu"
43
+ model = model.to(device)
44
+ print(f"Model loaded successfully on {device}!")
45
+ yield
46
 
47
 
48
  app = FastAPI(title="SkillXray Extraction API", lifespan=lifespan)
 
51
 
52
  @app.get("/")
53
  def read_root():
54
+ return {
55
+ "status": "online",
56
+ "message": "SkillXray Extraction API is running.",
57
+ }
58
+
59
+
60
+ def snap_to_word_boundaries(text: str, start: int, end: int) -> tuple[int, int]:
61
+ """Expand character indices outward to whitespace boundaries."""
62
+ while start > 0 and not text[start - 1].isspace():
63
+ start -= 1
64
+ while end < len(text) and not text[end].isspace():
65
+ end += 1
66
+ return start, end
67
+
68
+
69
+ def clean_and_validate_span(raw_span: str) -> str | None:
70
+ """Trim edge prepositions, punctuation, and discard noise."""
71
+ span = raw_span.strip(" \t\n\r,;:–—/&*()[]{}'\"")
72
+
73
+ # Strip edge words repeatedly
74
+ tokens = span.split()
75
+ while tokens and tokens[0].lower() in EDGE_WORDS:
76
+ tokens.pop(0)
77
+ while tokens and tokens[-1].lower() in EDGE_WORDS:
78
+ tokens.pop()
79
+
80
+ cleaned = " ".join(tokens).strip(" \t\n\r,;:–—/&*()[]{}'\"")
81
+
82
+ # Validation filters
83
+ if len(cleaned) < 2:
84
+ return None
85
+ if cleaned.lower() in EDGE_WORDS or cleaned.lower() in GENERIC_NOISE:
86
+ return None
87
+ # Must contain at least one alphanumeric character
88
+ if not any(c.isalnum() for c in cleaned):
89
+ return None
90
+ # Reject strings that are more than 70% punctuation or symbols
91
+ letters = sum(c.isalnum() for c in cleaned)
92
+ if letters / len(cleaned) < 0.5:
93
+ return None
94
+ # Reject overly long run-on sentences (duties, not skills)
95
+ if len(cleaned.split()) > 8:
96
+ return None
97
+
98
+ return cleaned
99
+
100
+
101
+ def extract_spans_from_window(text: str, enc, window_idx: int, probs: np.ndarray, tau: float) -> list[str]:
102
+ """Decodes token probabilities by grouping at the word-token level."""
103
+ offsets = enc["offset_mapping"][window_idx].tolist()
104
+ word_ids = enc.word_ids(batch_index=window_idx)
105
+
106
+ # 1. Group subwords into whole words
107
+ words = {}
108
+ word_order = []
109
+ for t_idx, w_idx in enumerate(word_ids):
110
+ if w_idx is None:
111
+ continue
112
+ s, e = offsets[t_idx]
113
+ if e <= s:
114
+ continue
115
+ if w_idx not in words:
116
+ words[w_idx] = [s, e, t_idx]
117
+ word_order.append(w_idx)
118
+ else:
119
+ words[w_idx][1] = max(words[w_idx][1], e)
120
+
121
+ if not word_order:
122
+ return []
123
+
124
+ # Model label IDs: O is 0, B-SKILL is 1, I-SKILL is 2
125
+ o_id = model.config.label2id.get("O", 0)
126
+ b_id = model.config.label2id.get("B-SKILL", 1)
127
+ i_id = model.config.label2id.get("I-SKILL", 2)
128
+
129
+ # 2. Extract sequences where P(skill) >= tau
130
+ extracted = []
131
+ current_span = None
132
+
133
+ for w_idx in word_order:
134
+ s, e, t_idx = words[w_idx]
135
+ p = probs[t_idx]
136
+ p_skill = 1.0 - float(p[o_id])
137
+ is_begin = bool(p[b_id] >= p[i_id])
138
+
139
+ if p_skill >= tau:
140
+ if current_span is None or is_begin:
141
+ if current_span is not None:
142
+ extracted.append(current_span)
143
+ current_span = {"start": s, "end": e}
144
+ else:
145
+ current_span["end"] = e
146
+ else:
147
+ if current_span is not None:
148
+ extracted.append(current_span)
149
+ current_span = None
150
+
151
+ if current_span is not None:
152
+ extracted.append(current_span)
153
+
154
+ # 3. Snap to full word boundaries and clean
155
+ valid_skills = []
156
+ for sp in extracted:
157
+ snapped_s, snapped_e = snap_to_word_boundaries(text, sp["start"], sp["end"])
158
+ candidate = text[snapped_s:snapped_e]
159
+ cleaned = clean_and_validate_span(candidate)
160
+ if cleaned:
161
+ valid_skills.append(cleaned)
162
+
163
+ return valid_skills
164
+
165
+
166
+ def extract_from_text(text: str) -> list[str]:
167
+ cleaned_input = re.sub(r"[\r\n]+", "\n", text).strip()
168
+ if not cleaned_input:
169
+ return []
170
+
171
+ enc = tokenizer(
172
+ cleaned_input,
173
+ truncation=True,
174
+ max_length=MAX_LEN,
175
+ stride=STRIDE,
176
+ return_overflowing_tokens=True,
177
+ return_offsets_mapping=True,
178
+ padding="max_length",
179
+ return_tensors="pt",
180
+ )
181
+ enc.pop("overflow_to_sample_mapping", None)
182
+
183
+ num_windows = enc["input_ids"].shape[0]
184
+ all_skills = []
185
+
186
+ for i in range(0, num_windows, BATCH):
187
+ batch = {
188
+ "input_ids": enc["input_ids"][i:i + BATCH].to(device),
189
+ "attention_mask": enc["attention_mask"][i:i + BATCH].to(device)
190
+ }
191
+ with torch.no_grad():
192
+ logits = model(**batch).logits
193
+ probs = torch.softmax(logits, dim=-1).cpu().numpy()
194
+
195
+ for w in range(probs.shape[0]):
196
+ window_skills = extract_spans_from_window(
197
+ cleaned_input, enc, i + w, probs[w], TAU
198
+ )
199
+ all_skills.extend(window_skills)
200
+
201
+ # Preserve order and eliminate case-insensitive duplicates
202
+ unique_skills = []
203
+ seen = set()
204
+ for s in all_skills:
205
+ key = s.casefold()
206
+ if key not in seen:
207
+ seen.add(key)
208
+ unique_skills.append(s)
209
+
210
+ return unique_skills
211
 
212
 
213
  @app.post("/api/v1/extract-skills")
 
215
  payload: dict,
216
  credentials: HTTPAuthorizationCredentials = Security(security),
217
  ):
218
+ if MODEL_API_KEY and credentials.credentials != MODEL_API_KEY:
219
+ raise HTTPException(status_code=401, detail="Invalid authorization token.")
220
+ if not model or not tokenizer:
221
+ raise HTTPException(
222
+ status_code=503,
223
+ detail="Model is still initializing. Please try again in a moment.",
224
+ )
225
+
226
+ text = payload.get("text", "")
227
+ if not text:
228
+ raise HTTPException(status_code=400, detail="Text field is required.")
229
+
230
+ skills = extract_from_text(text[:MAX_CHARS])
231
+ return {"skills": skills, "count": len(skills)}