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

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +73 -55
main.py CHANGED
@@ -1,32 +1,36 @@
1
  from contextlib import asynccontextmanager
2
  import os
 
3
  import torch
4
  from fastapi import FastAPI, HTTPException, Security
5
  from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
6
  from transformers import AutoModelForTokenClassification, AutoTokenizer
7
 
8
- # Global variables for model and tokenizer
9
  tokenizer = None
10
  model = None
 
11
 
12
  MODEL_REPO = os.getenv("MODEL_REPO", "Tracymgprog/skillxray_skill_extraction")
13
  MODEL_API_KEY = os.getenv("MODEL_API_KEY", "")
14
 
 
 
 
 
 
15
 
16
  @asynccontextmanager
17
  async def lifespan(app: FastAPI):
18
- global tokenizer, model
19
- print(
20
- f"Loading fine-tuned model and tokenizer from Hugging Face Hub:"
21
- f" {MODEL_REPO}..."
22
- )
23
 
24
- tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, use_fast=False)
 
25
  model = AutoModelForTokenClassification.from_pretrained(MODEL_REPO)
26
  model.eval()
27
 
28
- if torch.cuda.is_available():
29
- model = model.cuda()
30
 
31
  print("Model and tokenizer loaded successfully!")
32
  yield
@@ -36,16 +40,72 @@ app = FastAPI(title="SkillXray Extraction API", lifespan=lifespan)
36
  security = HTTPBearer()
37
 
38
 
39
- # ADDED THIS ROOT ENDPOINT FOR HEALTH CHECKS
40
  @app.get("/")
41
  def read_root():
42
  return {
43
  "status": "online",
44
- "message": "SkillXray Extraction API is running. Send POST requests to"
45
- " /api/v1/extract-skills",
46
  }
47
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  @app.post("/api/v1/extract-skills")
50
  async def extract_skills(
51
  payload: dict,
@@ -64,47 +124,5 @@ async def extract_skills(
64
  if not text:
65
  raise HTTPException(status_code=400, detail="Text field is required.")
66
 
67
- inputs = tokenizer(
68
- text,
69
- return_tensors="pt",
70
- truncation=True,
71
- max_length=160,
72
- return_offsets_mapping=True,
73
- )
74
- offset_mapping = inputs.pop("offset_mapping")[0]
75
-
76
- if torch.cuda.is_available():
77
- inputs = {k: v.cuda() for k, v in inputs.items()}
78
-
79
- with torch.no_grad():
80
- outputs = model(**inputs)
81
- predictions = torch.argmax(outputs.logits, dim=-1)[0]
82
-
83
- extracted_skills = []
84
- current_start = None
85
- current_end = None
86
-
87
- for idx, pred in enumerate(predictions.cpu().numpy()):
88
- start, end = int(offset_mapping[idx][0]), int(offset_mapping[idx][1])
89
-
90
- if int(pred) in (1, 2): # B-SKILL or I-SKILL
91
- if start < end:
92
- if current_start is None:
93
- current_start = start
94
- current_end = end
95
- else:
96
- if current_start is not None and current_end is not None:
97
- skill_text = text[current_start:current_end].replace("##", "").strip()
98
- if len(skill_text) > 1:
99
- extracted_skills.append(skill_text)
100
- current_start = None
101
- current_end = None
102
-
103
- if current_start is not None and current_end is not None:
104
- skill_text = text[current_start:current_end].replace("##", "").strip()
105
- if len(skill_text) > 1:
106
- extracted_skills.append(skill_text)
107
-
108
- unique_skills = list(dict.fromkeys(extracted_skills))
109
-
110
  return {"skills": unique_skills, "count": len(unique_skills)}
 
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
10
  model = None
11
+ 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
 
40
  security = HTTPBearer()
41
 
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")
110
  async def extract_skills(
111
  payload: dict,
 
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)}