mrfirdauss commited on
Commit
9a6af66
·
verified ·
1 Parent(s): 04d4921

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. Dockerfile +12 -0
  2. app.py +87 -0
  3. classificator.py +11 -0
  4. extractor.py +159 -0
  5. models.py +35 -0
  6. requirements.txt +8 -0
Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:latest
2
+ COPY . .
3
+ WORKDIR /
4
+
5
+ RUN pip install --no-cache-dir --upgrade -r /requirements.txt
6
+
7
+ ENV API_KEY=${API_KEY}
8
+
9
+ ENV TRANSFORMERS_CACHE=/transformers_cache
10
+ RUN mkdir -p /transformers_cache && chmod -R 777 /transformers_cache
11
+
12
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from models import CVExtracted, InsertedText, JobAndCV, ClassificationResult, InsertedLink
3
+ import os
4
+ from io import BytesIO
5
+ import extractor
6
+ from datetime import datetime
7
+ from PyPDF2 import PdfReader
8
+ import requests
9
+ import classificator
10
+
11
+ os.environ['TRANSFORMERS_CACHE'] = '/transformers_cache'
12
+ os.environ['HF_HOME'] = '/transformers_cache'
13
+
14
+
15
+
16
+ app = FastAPI()
17
+ @app.get("/", response_model=dict[str, str])
18
+ def getall():
19
+ return {"hello":"world"}
20
+
21
+
22
+ @app.post("/ext", response_model=CVExtracted)
23
+ async def extract(text: InsertedText):
24
+ dictresult = extractor.predict(text.text)
25
+ return CVExtracted(**dictresult)
26
+
27
+
28
+ @app.post("/classify", response_model=ClassificationResult)
29
+ async def classify(body:JobAndCV ):
30
+ mininmal_start = 0
31
+ maximal_end = 0
32
+ positions = []
33
+ userMajors = []
34
+ if len(body.cv.experiences) > 0:
35
+ mininmal_start = datetime.strptime(body.cv.experiences[0]['start'], "%Y-%m-%d").date() if body.cv.experiences[0].get('start') != None else datetime.today().date()
36
+ maximal_end = datetime.strptime(body.cv.experiences[0]['end'], "%Y-%m-%d").date()
37
+ for exp in body.cv.experiences:
38
+ positions.append(exp['position'])
39
+ if exp.get('end') == None:
40
+ exp['end'] = datetime.today().strftime("%Y-%m-%d")
41
+ if datetime.strptime(exp['start'], "%Y-%m-%d").date() < mininmal_start:
42
+ mininmal_start = datetime.strptime(exp['start'], "%Y-%m-%d").date()
43
+ if datetime.strptime(exp['end'], "%Y-%m-%d").date() > maximal_end:
44
+ maximal_end = datetime.strptime(exp['end'], "%Y-%m-%d").date()
45
+ else:
46
+ mininmal_start = 0
47
+ maximal_end = 0
48
+
49
+ for edu in body.cv.educations:
50
+ userMajors.append(edu['major'])
51
+
52
+ yoe = (maximal_end - mininmal_start).days//365
53
+ cv = {
54
+ "experiences": str(body.cv.experiences),
55
+ "positions": str(positions),
56
+ "userMajors": str(userMajors),
57
+ "skills": str(body.cv.skills),
58
+ "yoe": yoe
59
+ }
60
+ job = {
61
+ "jobDesc": body.job.jobDesc,
62
+ "role": body.job.role,
63
+ "majors": str(body.job.majors),
64
+ "skills": str(body.job.skills),
65
+ "minYoE": body.job.minYoE
66
+ }
67
+ results = classificator.predict(cv, job)
68
+ return ClassificationResult(**results)
69
+
70
+ @app.post("/cv", response_model=CVExtracted)
71
+ async def extract(link: InsertedLink):
72
+ response = requests.get(link.link)
73
+ if response.status_code == 200:
74
+ # Open the PDF from bytes in memory
75
+ pdf_reader = PdfReader(BytesIO(response.content))
76
+ number_of_pages = len(pdf_reader.pages)
77
+ # Optionally, read text from the first page
78
+ page = pdf_reader.pages[0]
79
+ text = page.extract_text()
80
+ for i in range(1, number_of_pages):
81
+ text+= '\n' + pdf_reader.pages[i].extract_text()
82
+ else:
83
+ #return error, make 500 because file server error
84
+ raise HTTPException(status_code=response.status_code, detail="File server error")
85
+
86
+ dictresult = extractor.predict(text)
87
+ return CVExtracted(**dictresult)
classificator.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sentence_transformers import SentenceTransformer
2
+ from sklearn.metrics.pairwise import cosine_similarity
3
+
4
+ st = SentenceTransformer('all-mpnet-base-v2')
5
+
6
+ def predict(cv, job):
7
+ diffYoe = cv.yoe - job.minimumYoe
8
+ results = {}
9
+ results['score'] = 0.6
10
+ results['is_accepted'] = True
11
+ return results
extractor.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import RobertaTokenizerFast, AutoModelForTokenClassification
2
+ import re
3
+ import torch
4
+
5
+ tokenizer = RobertaTokenizerFast.from_pretrained("mrfirdauss/robert-base-finetuned-cv")
6
+ model = AutoModelForTokenClassification.from_pretrained("mrfirdauss/robert-base-finetuned-cv")
7
+
8
+ id2label = {0: 'O',
9
+ 1: 'B-NAME',
10
+ 3: 'B-NATION',
11
+ 5: 'B-EMAIL',
12
+ 7: 'B-URL',
13
+ 9: 'B-CAMPUS',
14
+ 11: 'B-MAJOR',
15
+ 13: 'B-COMPANY',
16
+ 15: 'B-DESIGNATION',
17
+ 17: 'B-GPA',
18
+ 19: 'B-PHONE NUMBER',
19
+ 21: 'B-ACHIEVEMENT',
20
+ 23: 'B-EXPERIENCES DESC',
21
+ 25: 'B-SKILLS',
22
+ 27: 'B-PROJECTS',
23
+ 2: 'I-NAME',
24
+ 4: 'I-NATION',
25
+ 6: 'I-EMAIL',
26
+ 8: 'I-URL',
27
+ 10: 'I-CAMPUS',
28
+ 12: 'I-MAJOR',
29
+ 14: 'I-COMPANY',
30
+ 16: 'I-DESIGNATION',
31
+ 18: 'I-GPA',
32
+ 20: 'I-PHONE NUMBER',
33
+ 22: 'I-ACHIEVEMENT',
34
+ 24: 'I-EXPERIENCES DESC',
35
+ 26: 'I-SKILLS',
36
+ 28: 'I-PROJECTS'}
37
+
38
+ def merge_subwords(tokens, labels):
39
+ merged_tokens = []
40
+ merged_labels = []
41
+
42
+ current_token = ""
43
+ current_label = ""
44
+
45
+ for token, label in zip(tokens, labels):
46
+ if token.startswith("Ġ"):
47
+ if current_token:
48
+ # Append the accumulated subwords as a new token and label
49
+ merged_tokens.append(current_token)
50
+ merged_labels.append(current_label)
51
+ # Start a new token and label
52
+ current_token = token[1:] # Remove the 'Ġ'
53
+ current_label = label
54
+ else:
55
+ # Continue accumulating subwords into the current token
56
+ current_token += token
57
+
58
+ # Append the last token and label
59
+ if current_token:
60
+ merged_tokens.append(current_token)
61
+ merged_labels.append(current_label)
62
+
63
+ return merged_tokens, merged_labels
64
+
65
+ def chunked_inference(text, tokenizer, model, max_length=512):
66
+ # Tokenize the text with truncation=False to get the full list of tokens
67
+ tok = re.findall(r'\w+|[^\w\s]', text, re.UNICODE)
68
+ tokens = tokenizer.tokenize(tok, is_split_into_words=True)
69
+ # Initialize containers for tokenized inputs
70
+ input_ids_chunks = []
71
+ # Decode and print each token
72
+ print(tokens)
73
+ # Create chunks of tokens that fit within the model's maximum input size
74
+ for i in range(0, len(tokens), max_length - 2): # -2 accounts for special tokens [CLS] and [SEP]
75
+ chunk = tokens[i:i + max_length - 2]
76
+ # Encode the chunks. Add special tokens via the tokenizer
77
+ chunk_ids = tokenizer.convert_tokens_to_ids(chunk)
78
+ chunk_ids = tokenizer.build_inputs_with_special_tokens(chunk_ids)
79
+ input_ids_chunks.append(chunk_ids)
80
+
81
+ # Convert list of token ids into a tensor
82
+ input_ids_chunks = [torch.tensor(chunk_ids).unsqueeze(0) for chunk_ids in input_ids_chunks]
83
+
84
+ # Predictions container
85
+ predictions = []
86
+
87
+ # Process each chunk
88
+ for input_ids in input_ids_chunks:
89
+ attention_mask = torch.ones_like(input_ids) # Create an attention mask for the inputs
90
+ output = model(input_ids, attention_mask=attention_mask)
91
+ logits = output[0] if isinstance(output, tuple) else output.logits
92
+ predictions_chunk = torch.argmax(logits, dim=-1).squeeze(0)
93
+ predictions.append(predictions_chunk[1:-1])
94
+
95
+ # Optionally, you can convert predictions to labels here
96
+ # Flatten the list of tensors into one long tensor for label mapping
97
+ predictions = torch.cat(predictions, dim=0)
98
+ predicted_labels = [id2label[pred.item()] for pred in predictions]
99
+ return merge_subwords(tokens,predicted_labels)
100
+
101
+ def process_tokens(tokens, tag_prefix):
102
+ # Process tokens to extract entities based on the tag prefix
103
+ entities = []
104
+ current_entity = {}
105
+ for token, tag in tokens:
106
+ if tag.startswith('B-') and tag.endswith(tag_prefix):
107
+ # Start a new entity
108
+ if current_entity:
109
+ # Append the current entity before starting a new one
110
+ entities.append(current_entity)
111
+ current_entity = {}
112
+ current_entity['text'] = token
113
+ current_entity['type'] = tag
114
+ elif tag.startswith('I-') and (tag.endswith('GPA') or tag.endswith('URL')) and current_entity:
115
+ current_entity['text'] += '' + token
116
+ elif tag.startswith('I-') and tag.endswith(tag_prefix) and current_entity:
117
+ # Continue the current entity
118
+ current_entity['text'] += ' ' + token
119
+ # Append the last entity if there is one
120
+ if current_entity:
121
+ entities.append(current_entity)
122
+ return entities
123
+
124
+ def predict(text):
125
+ tokens, predictions = chunked_inference(text, tokenizer, model)
126
+ data = list(zip(tokens, predictions))
127
+ profile = {
128
+ "name": "",
129
+ "links": [],
130
+ "skills": [],
131
+ "experiences": [],
132
+ "educations": []
133
+ }
134
+ profile['name'] = ' '.join([t for t, p in data if p.endswith('NAME')])
135
+
136
+ for skills in process_tokens(data, 'SKILLS'):
137
+ profile['skills'].append(skills['text'])
138
+ #Links
139
+ for links in process_tokens(data, 'URL'):
140
+ profile['links'].append(links['text'])
141
+ # Process experiences and education
142
+ for designation, company, experience_desc in zip(process_tokens(data, 'DESIGNATION'),process_tokens(data, 'CAMPUS'),process_tokens(data, 'EXPERIENCES DESC') ):
143
+ profile['experiences'].append({
144
+ "start": None,
145
+ "end": None,
146
+ "designation": designation['text'],
147
+ "company": company['text'], # To be filled in similarly
148
+ "experience_description": experience_desc['text'] # To be filled in similarly
149
+ })
150
+ for major, gpa, campus in zip(process_tokens(data, 'MAJOR'), process_tokens(data, 'GPA'), process_tokens(data, 'CAMPUS')):
151
+ profile['educations'].append({
152
+ "start": None,
153
+ "end": None,
154
+ "major": major['text'],
155
+ "campus": campus['text'], # To be filled in similarly
156
+ "GPA": gpa['text'] # To be filled in similarly
157
+ })
158
+
159
+ return profile
models.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import List, Optional, Any
3
+
4
+ class CVExtracted(BaseModel):
5
+ name: str = Field(...)
6
+ skills: List[str] = Field(...)
7
+ links: List[str] = Field(...)
8
+ experiences: List[dict[str, Any]] = Field(...)
9
+ educations: List[dict[str, Any]] = Field(...)
10
+
11
+ class InsertedText(BaseModel):
12
+ text: str
13
+
14
+ class CVToClassify(BaseModel):
15
+ educations: List[dict[str, Any]]
16
+ skills: List[str]
17
+ experiences: List[dict[str, Any]]
18
+
19
+ class JobToClassify(BaseModel):
20
+ minYoE: int
21
+ jobDesc: str
22
+ skills: List[str]
23
+ role: str
24
+ majors: List[str]
25
+
26
+
27
+ class JobAndCV(BaseModel):
28
+ cv: CVToClassify
29
+ job: JobToClassify
30
+
31
+ class ClassificationResult(BaseModel):
32
+ score: float
33
+ is_accepted: bool
34
+ class InsertedLink(BaseModel):
35
+ link: str
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ pydantic
3
+ fastapi
4
+ transformers
5
+ uvicorn[standard]
6
+ PyPDF2
7
+ sentence_transformers
8
+ scikit-learn