File size: 32,119 Bytes
ceba096
2965550
ceba096
 
 
 
2965550
 
 
 
 
ea32026
 
 
2965550
ceba096
 
ea32026
 
 
 
ceba096
 
 
 
2965550
ceba096
ea32026
 
 
ceba096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56c05e7
 
 
 
ceba096
 
 
 
 
 
56c05e7
 
 
 
 
ceba096
 
 
 
 
 
56c05e7
ceba096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea32026
 
 
 
 
 
 
 
 
 
 
 
ad4ea7b
ea32026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb8e442
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea32026
ceba096
 
 
 
 
ea32026
 
 
ceba096
 
 
ea32026
ceba096
 
 
 
ea32026
ceba096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
from typing import Dict, List, Any

import spacy
from spacy.matcher import PhraseMatcher
from skillNer.general_params import SKILL_DB
from skillNer.skill_extractor_class import SkillExtractor

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import LongformerTokenizer, LongformerModel
import requests
import os
from dotenv import load_dotenv

import re
from datetime import datetime
import time

# Load environment variables from .env.local
load_dotenv('.env.local')

Resume_num_labels = None
class EndpointHandler():
    def __init__(self, path=""):
        # Label mapping as provided
        # Resume Label Mapping
        self.hf_token = os.getenv('HUGGINGFACE_TOKEN')
        if not self.hf_token:
            print("Warning: HUGGINGFACE_TOKEN environment variable not set")
        self.Resume_label_map = {
            "RT": 0,    # Resume Title
            "SST": 1,   # Summary Section Title
            "SSC": 2,   # Summary Section Content
            "AST": 3,   # Accomplishments Section Title
            "ASC": 4,   # Accomplishments Section Content
            "EDST": 5,  # Education Section Title
            "EDSC": 6,  # Education Section Content
            "SKST": 7,  # Skills Section Title
            "SKSC": 8,  # Skills Section Content
            "HST": 9,   # Highlights Section Title
            "HSC": 10,  # Highlights Section Content
            "CST": 11,  # Certifications Section Title
            "CSC": 12,  # Certifications Section Content
            "EST": 13,  # Experience Section Title
            "EJT": 14,  # Experience Job Title
            "EDT": 15,  # Experience Date Range Title
            "ECT": 16,  # Experience Company Title
            "EDC": 17   # Experience Description Content
        }
        global Resume_num_labels
        self.Resume_num_labels = len(self.Resume_label_map)
        Resume_num_labels = self.Resume_num_labels

        self.Resume_labels = [
            {"value": "RT", "label": "Resume Title"},
            {"value": "SST", "label": "Summary Section Title"},
            {"value": "SSC", "label": "Summary Section Content"},
            {"value": "AST", "label": "Accomplishments Section Title"},
            {"value": "ASC", "label": "Accomplishments Section Content"},
            {"value": "EDST", "label": "Education Section Title"},
            {"value": "EDSC", "label": "Education Section Content"},
            {"value": "SKST", "label": "Skills Section Title"},
            {"value": "SKSC", "label": "Skills Section Content"},
            {"value": "HST", "label": "Highlights Section Title"},
            {"value": "HSC", "label": "Highlights Section Content"},
            {"value": "CST", "label": "Certifications Section Title"},
            {"value": "CSC", "label": "Certifications Section Content"},
            {"value": "EST", "label": "Experience Section Title"},
            {"value": "EJT", "label": "Experience Job Title"},
            {"value": "EDT", "label": "Experience Date Range Title"},
            {"value": "ECT", "label": "Experience Company Title"},
            {"value": "EDC", "label": "Experience Description Content"}
        ]


        self.Resume_tokenizer = LongformerTokenizer.from_pretrained("allenai/longformer-base-4096")
        self.Resume_tokenizer.cls_token

        # Load model architecture
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.Resume_model = LongformerSentenceClassifier(num_labels=Resume_num_labels)
        self.Resume_model.to(self.device)
        # Load trained weights
        self.Resume_model.load_state_dict(torch.load(path + "/ResumeSegmentClassifier8thEpochV3.pth", map_location=self.device))

        # Set model to evaluation mode
        self.Resume_model.eval()
        nlp = spacy.load("en_core_web_lg")
        self.skill_extractor = SkillExtractor(nlp, SKILL_DB, PhraseMatcher)


    def predict_resume_sections(self, model, text, tokenizer, device):
        model.eval()

        # Tokenize text and get input tensors
        encoding = tokenizer(
            text,
            return_tensors="pt",
            truncation=True,
            padding="max_length",
            max_length=4096
        )

        input_ids = encoding["input_ids"].to(device)
        attention_mask = encoding["attention_mask"].to(device)

        # Identify `[CLS]` positions (assuming each sentence starts with `[CLS]`)
        cls_positions = (input_ids == tokenizer.cls_token_id).nonzero(as_tuple=True)[1]
        cls_positions = cls_positions.unsqueeze(0).to(device)  # Shape: (1, num_sentences)

        # Create global attention mask (Longformer requires at least 1 global attention token)
        global_attention_mask = torch.zeros_like(input_ids)
        global_attention_mask[:, cls_positions] = 1  # Assign global attention to `[CLS]` tokens

        # Run the model
        with torch.no_grad():
            logits = model(
                input_ids=input_ids,
                attention_mask=attention_mask,
                global_attention_mask=global_attention_mask,
                cls_positions=cls_positions
            )  # Shape: (1, num_sentences, num_labels)

        logits = logits.squeeze(0)  # Shape: (num_sentences, num_labels)
        probs = F.softmax(logits, dim=-1)  # Convert logits to probabilities
        predictions = torch.argmax(probs, dim=-1)  # Get predicted label indices

        return predictions.cpu().numpy()  # Convert to NumPy array for easy use



    def capture_sentences(self, lines):
        combined_text = " ".join(lines)  # Merge all lines into one string
        sentences = re.split(r"(?<=\.)\s+|(?<=\!)\s+|(?<=\?)\s+", combined_text)  # Split by ., !, ?
        return [sentence.strip() for sentence in sentences if sentence.strip()]  # Remove extra spaces

    def extract_resume_sections(self, text):
        lines = text.splitlines()
        lines = [line for line in text.splitlines() if line.strip()]
        text = lines

        concatenated_text = " ".join(f"{self.Resume_tokenizer.cls_token} {sentence}" for sentence in text)

        predictions = self.predict_resume_sections(self.Resume_model, concatenated_text, self.Resume_tokenizer, self.device)
        return predictions, text

    def extract_resume_roles(self, text):
        lines = text.splitlines()
        lines = [line for line in text.splitlines() if line.strip()]
        text = lines

        concatenated_text = " ".join(f"{self.Resume_tokenizer.cls_token} {sentence}" for sentence in text)

        predictions = self.predict_resume_sections(self.Resume_model, concatenated_text, self.Resume_tokenizer, self.device)

        # Array of roles
        #  [
            # {"title": [], "description": []},
            # {"title": [], "description": []}
        #  ]
        roles = []

        i = -1
        for item in predictions[:len(predictions) - 1]:
            # ----- do not touch -----
            i+=1
            # If role array is empty, insert new role
            if len(roles) == 0 and self.Resume_labels[item]['value'] == "EJT":
                roles.append({"title": [lines[i]], "description": []})
                continue
            # if len(roles) == 0 and Resume_labels[item]['value'] == "EDC":
            #   roles.append({"title": [], "description": [lines[i]]})

            # If element is a title
            if self.Resume_labels[item]['value'] == "EJT":
                # If previous element doesn't have a description, append the title
                if len(roles[len(roles) - 1]["description"]) < 1:
                    roles[len(roles) - 1]["title"].append(lines[i])
                    continue
                # If previous element already has a description, create a new role
                if len(roles[len(roles) - 1]["description"]) > 0:
                    roles.append({"title": [lines[i]], "description": []})
                    continue

            # If element is a description, directly append to the last role in the array
            if self.Resume_labels[item]['value'] == "EDC":
                # If description is stuck between EJT, most likely it is an EJT
                if i - 1 > 0 and i + 1 < len(predictions) and self.Resume_labels[predictions[i - 1]]['value'] == "EJT" and self.Resume_labels[predictions[i + 1]]['value'] == "EJT":
                    roles[len(roles) - 1]["title"].append(lines[i])
                    continue
                if roles:
                    roles[-1]["description"].append(lines[i])
                else:
                    # Optionally, log the error or create a default role
                    print("Warning: Description found but no role header exists. Skipping this description.")

            # If element is not an EJT or EDC but stuck between EDC, most likely it is an EDC
            if self.Resume_labels[item]['value'] != "EDC" and self.Resume_labels[item]['value'] != "EJT":
                if i - 1 > 0 and i + 1 < len(predictions) and self.Resume_labels[predictions[i - 1]]['value'] == "EDC" and self.Resume_labels[predictions[i + 1]]['value'] == "EDC":
                    roles[-1]["description"].append(lines[i])

        # Cleaning description
        for item in roles:
            sentences = self.capture_sentences(item['description'])
            item['description'] = sentences

        return roles
    
    def parse_date(self, date_str):
        """Tries multiple formats to parse a date string into a datetime object.

        - Returns the current date if 'present' or 'current' is given.
        - Tries multiple formats and prompts if ambiguous.
        """

        # Handle cases like "present", "current"
        present_keywords = {"present", "current", "now", "today"}
        if date_str.strip().lower() in present_keywords:
            return datetime.today()  # Return the current date

        date_formats = [
            ("%b %Y", "MMM YYYY"),  # Jun 2022
            ("%B %Y", "MMMM YYYY"),  # June 2022
            ("%Y-%m-%d", "YYYY-MM-DD"),  # 2022-06-01
            ("%Y/%m/%d", "YYYY/MM/DD"),  # 2022/06/01
            ("%Y.%m.%d", "YYYY.MM.DD"),  # 2022.06.01
            ("%d-%m-%Y", "DD-MM-YYYY"),  # 01-06-2022
            ("%d/%m/%Y", "DD/MM/YYYY"),  # 01/06/2022
            ("%d.%m.%Y", "DD.MM.YYYY"),  # 01.06.2022
            ("%m-%d-%Y", "MM-DD-YYYY"),  # 06-01-2022 (US format)
            ("%m/%d/%Y", "MM/DD/YYYY"),  # 06/01/2022 (US format)
            ("%m.%d.%Y", "MM.DD.YYYY"),  # 06.01.2022
            ("%d %b %Y", "DD MMM YYYY"),  # 01 Jun 2022
            ("%d %B %Y", "DD MMMM YYYY"),  # 01 June 2022
            ("%b-%d-%Y", "MMM-DD-YYYY"),  # Jun-01-2022
            ("%b/%d/%Y", "MMM/DD/YYYY"),  # Jun/01/2022
            ("%B-%d-%Y", "MMMM-DD-YYYY"),  # June-01-2022
            ("%B/%d/%Y", "MMMM/DD/YYYY"),  # June/01/2022
            ("%d-%b-%Y", "DD-MMM-YYYY"),  # 01-Jun-2022
            ("%d/%b/%Y", "DD/MMM/YYYY"),  # 01/Jun/2022
            ("%d-%B-%Y", "DD-MMMM-YYYY"),  # 01-June-2022
            ("%d/%B/%Y", "DD/MMMM/YYYY"),  # 01/June/2022
            ("%Y", "YYYY"),  # 2022 (Only Year)
            ("%m/%Y", "MM/YYYY"),  # 06/2022
            ("%m-%Y", "MM-YYYY"),  # 06-2022
            ("%m.%Y", "MM.YYYY"),  # 06.2022
            ("%Y%m%d", "YYYYMMDD"),  # 20220601 (Compact format)
            ("%d%m%Y", "DDMMYYYY"),  # 01062022 (Compact format)
            ("%m%d%Y", "MMDDYYYY"),  # 06012022 (Compact format)
            ("%Y-%b-%d", "YYYY-MMM-DD"),  # 2022-Jun-01
            ("%Y/%b/%d", "YYYY/MMM/DD"),  # 2022/Jun/01
            ("%Y-%B-%d", "YYYY-MMMM-DD"),  # 2022-June-01
            ("%Y/%B/%d", "YYYY/MMMM/DD"),  # 2022/June/01
            ("%d-%b-%y", "DD-MMM-YY"),  # 01-Jun-22 (Two-digit year)
            ("%d/%b/%y", "DD/MMM/YY"),  # 01/Jun/22 (Two-digit year)
            ("%d-%B-%y", "DD-MMMM-YY"),  # 01-June-22 (Two-digit year)
            ("%d/%B/%y", "DD/MMMM/YY"),  # 01/June/22 (Two-digit year)
            ("%d-%m-%y", "DD-MM-YY"),  # 01-06-22 (Two-digit year)
            ("%d/%m/%y", "DD/MM/YY"),  # 01/06/22 (Two-digit year)
            ("%m-%d-%y", "MM-DD-YY"),  # 06-01-22 (US format with two-digit year)
            ("%m/%d/%y", "MM/DD/YY"),  # 06/01/22 (US format with two-digit year)
            ("%A, %d %B %Y", "Day, DD MMMM YYYY"),  # Wednesday, 01 June 2022
            ("%a, %d %b %Y", "Day Abbr, DD MMM YYYY"),  # Wed, 01 Jun 2022
        ]

        possible_dates = []

        for fmt, fmt_name in date_formats:
            try:
                parsed_date = datetime.strptime(date_str, fmt)
                possible_dates.append((parsed_date, fmt_name))
            except ValueError:
                continue  # Try next format

        # No valid format found
        if not possible_dates:
            # raise ValueError(f"Could not parse the date: {date_str}")
            return []

        # If only one valid interpretation, return it
        if len(possible_dates) == 1:
            return possible_dates[0][0]  # Return datetime object

        # If multiple interpretations exist, prompt user
        print(f"Ambiguous date: '{date_str}' could mean:")
        for idx, (date, fmt_name) in enumerate(possible_dates):
            print(f"{idx + 1}. {date.strftime('%Y-%m-%d')} ({fmt_name})")

        print("Defaulted to: ", possible_dates[0][1])
        return possible_dates[0][0]  # Return chosen date
    
    def extract_dates_from_context(self, context):
        """Extract dates from context using the date extraction endpoint."""
        max_retries = 5  # Increased retries for startup
        retry_delay = 5  # Increased delay for startup
        startup_delay = 10  # Longer delay for startup state
        
        for attempt in range(max_retries):
            try:
                headers = {
                    "Authorization": f"Bearer {self.hf_token}"
                }
                response = requests.post(
                    "https://iprlg93qeghlgufi.us-east-1.aws.endpoints.huggingface.cloud",
                    json={"inputs": context},
                    headers=headers,
                    timeout=30
                )
                
                if response.status_code == 200:
                    return response.json()
                elif response.status_code == 503:
                    if attempt < max_retries - 1:
                        if attempt == 0:
                            print(f"Service temporarily unavailable (503). Waiting 20 seconds... (Attempt {attempt + 1}/{max_retries})")
                            time.sleep(20)
                        else:
                            print(f"Service temporarily unavailable (503). Waiting 2 seconds... (Attempt {attempt + 1}/{max_retries})")
                            time.sleep(2)
                        continue
                    else:
                        print("Service unavailable after maximum retries")
                        return {"start_date": None, "end_date": None}
                elif response.status_code == 404:
                    print("Endpoint not found. Please check if the endpoint URL is correct.")
                    return {"start_date": None, "end_date": None}
                elif response.status_code == 401:
                    print("Authentication failed. Please check your Hugging Face token.")
                    return {"start_date": None, "end_date": None}
                else:
                    print(f"Error calling date extraction endpoint: {response.status_code}")
                    print(f"Response: {response.text}")
                    return {"start_date": None, "end_date": None}
                    
            except requests.exceptions.Timeout:
                print(f"Request timed out. Attempt {attempt + 1}/{max_retries}")
                if attempt < max_retries - 1:
                    time.sleep(retry_delay)
                    continue
                return {"start_date": None, "end_date": None}
            except Exception as e:
                print(f"Exception while calling date extraction endpoint: {str(e)}")
                if attempt < max_retries - 1:
                    time.sleep(retry_delay)
                    continue
                return {"start_date": None, "end_date": None}
        
        return {"start_date": None, "end_date": None}
    
    def extract_length(self, start_date, end_date):
        """
        Args:
            start_date (datetime): The earlier date.
            end_date (datetime): The later date.

        Returns:
            int: Number of full months between the dates.
        """
        try:
            if start_date > end_date:
            # raise ValueError("start_date must be before end_date")
                return 0
        except:
            return 0

        # Calculate difference in years and months
        year_diff = end_date.year - start_date.year
        month_diff = end_date.month - start_date.month

        # Total months difference
        total_months = year_diff * 12 + month_diff
        return total_months

    def label_resume(self, text):
        results = self.extract_resume_roles(text)
        for item in results:
            # Extracting dates
            context = (" ".join(item["title"]))
            dates = self.extract_dates_from_context(context)
            date_started = dates.get("start_date")
            date_ended = dates.get("end_date")

            # Try parsing the dates; default to 0 for role_length if parsing fails.
            try:
                date_started_formatted = self.parse_date(date_started) if date_started else None
            except ValueError:
                date_started_formatted = None

            try:
                date_ended_formatted = self.parse_date(date_ended) if date_ended else None
            except ValueError:
                date_ended_formatted = None

            try:
                role_length = self.extract_length(date_started_formatted, date_ended_formatted)
            except:
                role_length = 0
            item["dates"] = {"date_started": date_started, "date_ended": date_ended}
            item["role_length"] = role_length

            # Extracting Skills
            item["skills"] = []
            seen = set()
            annotations = self.skill_extractor.annotate(" ".join(item["description"]))
            if 'results' in annotations and 'full_matches' in annotations['results']:
                for result in annotations['results']['full_matches']:
                    # Standardizing the skill names
                    skill_info = SKILL_DB.get(result["skill_id"], {})
                    skill_name = skill_info.get('skill_name', 'Unknown Skill')
                    if skill_name not in seen:
                        seen.add(skill_name)
                        item["skills"].append({'name': skill_name, 'skill_id': result["skill_id"]})
            if 'results' in annotations and 'ngram_scored' in annotations['results']:
                for result in annotations['results']['ngram_scored']:
                    if result['score'] >= 1:
                        # Standardizing the skill names
                        skill_info = SKILL_DB.get(result["skill_id"], {})
                        skill_name = skill_info.get('skill_name', 'Unknown Skill')
                    if skill_name not in seen:
                        seen.add(skill_name)
                        item["skills"].append({'name': skill_name, 'skill_id': result["skill_id"]})


        # for item in results:
        #   print(" -------- ROLE -------- ")
        #   print("Title: ", item["title"])
        #   print("Role Length: ", item["role_length"], " months")
        #   print("Dates: ", item["dates"])
        #   print("Skills: ", item["skills"])
        #   print("Description: ", item["description"])
        #   print("")
        #   print("")

        return results

        # SAMPLE OUTPUT
        # [
        # {
        # "title":  ['Full-stack Developer- Ospree.io - Jun. 2022 - Present (2 yrs, 1 mos)'],
        # "role_length":  33  months,
        # "dates":  {'date_started': 'Jun 2022', 'date_ended': 'Present'},
        # "skills":  [{'name': 'Cascading Style Sheets (CSS)', 'skill_id': 'KS121F45VPV8C9W3QFYH'}, {'name': 'JavaScript (Programming Language)', 'skill_id': 'KS1200771D9CR9LB4MWW'}, {'name': 'React.js', 'skill_id': 'KSDJCA4E89LB98JAZ7LZ'}, {'name': 'React Redux', 'skill_id': 'KSQOOX1S2DYD0E1VVZ5X'}, {'name': 'Integration', 'skill_id': 'KS125716TLTGH6SDHJD1'}, {'name': 'Custom Backend', 'skill_id': 'KS7R8G2D52QH187SED9R'}, {'name': 'Architectural Design', 'skill_id': 'KS120MG6W03JCFGKFHHC'}, {'name': 'Python (Programming Language)', 'skill_id': 'KS125LS6N7WP4S6SFTCK'}, {'name': 'PostgreSQL', 'skill_id': 'KS125TB6YR6236RKM563'}, {'name': 'SQLAlchemy', 'skill_id': 'KS440WD72WMZLQT09C91'}]
        # "description":  ['● Acted as the sole frontend developer that developed the frontend of all core features for the product using raw css,', 'javascript, ReactJS, React Query, and Redux, ensuring seamless integration with backend endpoints.', '● Built 3 out of 4 of the core backend modules based on the architecture designed by the software architect, utilizing Python,', 'FastAPI, PostgreSQL, and SQLAlchemy while integrating each module with third-party APIs.', 'database, ensuring data accuracy and availability for application use.', "● Contributed significantly to the development of the product, which played a key role in the startup's acceptance into", 'T echstars and securing USD$120K in funding.'],
        # }
        # ]

    def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
    data args:
            inputs (:obj: `str` | `PIL.Image` | `np.array`)
            kwargs
    Return:
            A :obj:`list` | `dict`: will be serialized and returned
        """
        text = data['inputs']
        # predictions, text = self.extract_job_sections(text)
        # requirements = self.extract_job_requirements(text)
        label_resume = self.label_resume(text)
        return label_resume
    

class LongformerSentenceClassifier(nn.Module):
    def __init__(self, model_name="allenai/longformer-base-4096", num_labels=Resume_num_labels):
        """
        Custom Longformer model for sentence classification.

        Args:
            model_name (str): Hugging Face Longformer model.
            num_labels (int): Number of possible sentence labels.
        """
        super(LongformerSentenceClassifier, self).__init__()
        self.longformer = LongformerModel.from_pretrained(model_name)
        self.classifier = nn.Linear(self.longformer.config.hidden_size, num_labels)

    def forward(self, input_ids, attention_mask, global_attention_mask, cls_positions):
        """
        Forward pass for sentence classification.

        Args:
            input_ids (Tensor): Tokenized input IDs, shape (batch_size, max_length)
            attention_mask (Tensor): Attention mask, shape (batch_size, max_length)
            global_attention_mask (Tensor): Global attention mask, shape (batch_size, max_length)
            cls_positions (List[Tensor]): Indices of `[CLS]` tokens for each batch element.
        """
        outputs = self.longformer(
            input_ids=input_ids,
            attention_mask=attention_mask,
            global_attention_mask=global_attention_mask
        )

        last_hidden_state = outputs.last_hidden_state
        cls_positions = cls_positions.view(input_ids.shape[0], -1)
        cls_embeddings = last_hidden_state.gather(1, cls_positions.unsqueeze(-1).expand(-1, -1, last_hidden_state.size(-1)))
        logits = self.classifier(cls_embeddings)

        return logits



if __name__ == "__main__":
    # init handler
    my_handler = EndpointHandler(path=".")

    # prepare sample payload
    payload = {"inputs": """
CASHIER


Professional Summary
Results-oriented, strategic sales professional with two years in the Retail industry. Cashier who is highly energetic, outgoing and detail-oriented. Handles multiple responsibilities simultaneously while providing exceptional customer service. Reliable and friendly team member who quickly learns and masters new concepts and skills. Passionate about helping customers and creating a satisfying shopping experience.


Core Qualifications
• Excellent multi-tasker
• Strong communication skills
• Flexible schedule
• Proficient in MS Office
Cash handling accuracy
Mathematical aptitude
Organized
Time management
Detail-oriented


Experience
Cashier
October 2014 to Current
Company Name - City , State
• Receive payment by cash, check, credit cards, vouchers, or automatic debits.
• Issue receipts, refunds, credits, or change due to customers.
• Assist customers by providing information and resolving their complaints.
• Establish or identify prices of goods, services or admission, and tabulate bills using 	calculators, cash registers, or optical price scanners.
• Greet customers entering establishments.
• Answer customers' questions, and provide information on procedures or policies.
• Process merchandise returns and exchanges.
• Maintain clean and orderly checkout areas and complete other general cleaning duties, 	such as mopping floors and emptying trash cans.
• Stock shelves, and mark prices on shelves and items.
• Count money in cash drawers at the beginning of shifts to ensure that amounts are 	correct and that there is adequate change.
• Calculate total payments received during a time period, and reconcile this with total sales.
• Monitor checkout stations to ensure that they have adequate cash available and that they 	are staffed appropriately.
• Assist with duties in other areas of the store, such as monitoring fitting rooms or bagging 	and carrying out customers' items.
• Sort, count, and wrap currency and coins.
• Compute and record totals of transactions.
• Compile and maintain non-monetary reports and records.
• Weigh items sold by weight to determine prices.
• Cash checks for customers.

Inbound/Return
June 2014 to September 2014
Company Name - City , State
Changed equipment over to new product.Maintained proper stock levels on a line.Helped achieve company goals by supporting production workers.

Cashier
February 2014 to June 2014
Company Name - City , State
• Receive payment by cash, check, credit cards, vouchers, or automatic debits.
• Issue receipts, refunds, credits, or change due to customers.
• Assist customers by providing information and resolving their complaints.
• Establish or identify prices of goods, services or admission, and tabulate bills using 	calculators, cash registers, or optical price scanners.
• Greet customers entering establishments.
• Answer customers' questions, and provide information on procedures or policies.
• Process merchandise returns and exchanges.
• Maintain clean and orderly checkout areas and complete other general cleaning duties, 	such as mopping floors and emptying trash cans.
• Stock shelves, and mark prices on shelves and items.
• Count money in cash drawers at the beginning of shifts to ensure that amounts are 	correct and that there is adequate change.
• Calculate total payments received during a time period, and reconcile this with total sales.
• Monitor checkout stations to ensure that they have adequate cash available and that they 	are staffed appropriately.
• Assist with duties in other areas of the store, such as monitoring fitting rooms or bagging 	and carrying out customers' items.
• Sort, count, and wrap currency and coins.
• Compute and record totals of transactions.
• Compile and maintain non-monetary reports and records.
• Weigh items sold by weight to determine prices.
• Cash checks for customers.

Apparel Associate
January 2014 to February 2014
Company Name - City , State
• Greet customers and ascertain what each customer wants or needs.
• Describe merchandise and explain use, operation, and care of merchandise to customers.
• Recommend, select, and help locate or obtain merchandise based on customer needs and 	desires.
• Compute sales prices, total purchases and receive and process cash or credit payment.
• Answer questions regarding the store and its merchandise.
• Maintain knowledge of current sales and promotions, policies regarding payment and 	exchanges, and security practices.
• Maintain records related to sales.
• Watch for and recognize security risks and thefts, and know how to prevent or handle 	these situations.
• Inventory stock and requisition new stock.
• Help customers try on or fit merchandise.
• Clean shelves, counters, and tables.
• Exchange merchandise for customers and accept returns.
• Open and close cash registers, performing tasks such as counting money, separating 	charge slips, coupons, and vouchers, balancing cash drawers, and making deposits.

Apparel Associate
October 2013 to December 2013
Company Name - City , State
• Greet customers and ascertain what each customer wants or needs.
• Describe merchandise and explain use, operation, and care of merchandise to customers.
• Recommend, select, and help locate or obtain merchandise based on customer needs and 	desires.
• Compute sales prices, total purchases and receive and process cash or credit payment.
• Answer questions regarding the store and its merchandise.
• Maintain knowledge of current sales and promotions, policies regarding payment and 	exchanges, and security practices.
• Maintain records related to sales.
• Watch for and recognize security risks and thefts, and know how to prevent or handle 	these situations.
• Inventory stock and requisition new stock.
• Help customers try on or fit merchandise.
• Clean shelves, counters, and tables.
• Exchange merchandise for customers and accept returns.
• Open and close cash registers, performing tasks such as counting money, separating charge slips, coupons, and vouchers, balancing cash drawers, and making deposits.

Cashier
August 2012 to August 2013
Company Name - City , State
• Receive payment by cash, check, credit cards, vouchers, or automatic debits.
• Issue receipts, refunds, credits, or change due to customers.
• Assist customers by providing information and resolving their complaints.
• Establish or identify prices of goods, services or admission, and tabulate bills using 	calculators, cash registers, or optical price scanners.
• Greet customers entering establishments.
• Answer customers' questions, and provide information on procedures or policies.
• Process merchandise returns and exchanges.
• Maintain clean and orderly checkout areas and complete other general cleaning duties, such as mopping floors and emptying trash cans.
• Stock shelves, and mark prices on shelves and items.
• Count money in cash drawers at the beginning of shifts to ensure that amounts are 	correct and that there is adequate change.
• Calculate total payments received during a time period, and reconcile this with total sales.
• Monitor checkout stations to ensure that they have adequate cash available and that they 	are staffed appropriately.
• Assist with duties in other areas of the store, such as monitoring fitting rooms or bagging and carrying out customers' items.
• Sort, count, and wrap currency and coins.
• Compute and record totals of transactions.
• Compile and maintain non-monetary reports and records.
• Weigh items sold by weight to determine prices.
• Cash checks for customers.


Education
5 2013
Member of FFA, FCA, Pep Club, and mentoring children from one of the public elementary schools


Skills
• Calculators
• Cash registers
• Credit, debit, checks and money
• Inventory
• Sales, scanners, tables
    """}
    # holiday_payload = {"inputs": "Today is a though day"}

    # test the handler
    non_holiday_pred=my_handler(payload)
    # holiday_payload=my_handler(holiday_payload)

    # show results
    print(non_holiday_pred)
    # print("holiday_payload", holiday_payload)