Spaces:
Sleeping
Sleeping
File size: 8,033 Bytes
478dec6 | 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 | # retrieve data dari table cv_raw, extract profile, insert profile ke table cv_profile_extracted
import json
import asyncio
from typing import ByteString, Dict, List
from services.llms.LLM import model_4o_2
from services.prompts.profile_extraction import extract_one_profile
from externals.databases._pgdb import fetch_data, execute_query
from models.data_model import OutProfile, Union
from utils.utils import pdf_reader, measure_runtime
query_get_cv_raw = "select profile_id, file_content " \
"from public.cv_raw " \
"where is_extracted = false " \
"limit {batch_size};"
query_get_cv_raw_excluded_id = "select profile_id, file_content " \
"from public.cv_raw " \
"where is_extracted = false " \
"and profile_id not in {failed_id}" \
"limit {batch_size};"
query_get_cv_raw_by_id = "select profile_id, file_content " \
"from public.cv_raw " \
"where profile_id = {profile_id};"
query_update_cv_raw = """
UPDATE cv_raw
SET is_extracted = true
WHERE profile_id = {profile_id};
"""
async def retrieve_raw_profiles(batch_size: int = 10, failed_id: List = []):
if failed_id == []:
query = query_get_cv_raw.format(batch_size=batch_size)
else:
query = query_get_cv_raw_excluded_id.format(failed_id=tuple(failed_id), batch_size=batch_size)
data = await fetch_data(query)
return data
async def retrieve_raw_profiles_by_id(id: int):
query = query_get_cv_raw_by_id.format(profile_id=id)
data = await fetch_data(query)
return data
async def update_raw_profile(profile_id: int):
query = query_update_cv_raw.format(profile_id=profile_id)
await execute_query(query)
@measure_runtime
async def extract_profile(file:ByteString):
cv = await pdf_reader(file)
llm = model_4o.with_structured_output(OutProfile)
chain = extract_one_profile | llm
input_chain = {
"cv":cv
}
profile = await chain.ainvoke(input_chain, config=None)
return profile
def sanitize_type(data:Dict):
data_mutated = data.copy()
neutralized_mapper = {
'fullname' : "-",
'high_edu_univ_1' : "-",
'high_edu_major_1' : "-",
'high_edu_gpa_1' : 0,
'high_edu_univ_2' : "-",
'high_edu_major_2' : "-",
'high_edu_gpa_2' : 0,
'high_edu_univ_3' : "-",
'high_edu_major_3' : "-",
'high_edu_gpa_3' : 0,
'domicile' : "-",
'yoe' : 0,
'hardskills' : [],
'softskills' : [],
'certifications' : [],
'business_domain_experiences': []
}
for k, v in data_mutated.items():
if v is None or (type(v) == str and v.lower() in ['null', '']):
data_mutated[k] = neutralized_mapper[k]
return data_mutated
def helper_handle_list_to_text(data:Dict, cols:List):
data_mutated = data.copy()
for col in cols:
if col in data_mutated:
if type(data_mutated[col]) == list and data_mutated[col] != []:
data_mutated[col] = ", ".join([p for p in data_mutated[col]])
elif type(data_mutated[col]) == list and data_mutated[col] == []:
data_mutated[col] = "-"
return data_mutated
query_insert_profile_extracted = """
insert into cv_profile_extracted
("fullname", "profile_id",
"univ_edu_1", "major_edu_1", "gpa_edu_1",
"univ_edu_2", "major_edu_2", "gpa_edu_2",
"univ_edu_3", "major_edu_3", "gpa_edu_3",
"domicile", "yoe",
"hardskills", "softskills", "certifications", "business_domain")
values
('{fullname}', {profile_id},
'{high_edu_univ_1}', '{high_edu_major_1}', {high_edu_gpa_1},
'{high_edu_univ_2}', '{high_edu_major_2}', {high_edu_gpa_2},
'{high_edu_univ_3}', '{high_edu_major_3}', {high_edu_gpa_3},
'{domicile}', {yoe},
'{hardskills}', '{softskills}', '{certifications}', '{business_domain_experiences}');
"""
async def wrap_extract_profile(file:ByteString, profile_id: Union[int, str], failed_id: List = []):
try:
extracted_profile = await extract_profile(file)
extracted_profile = sanitize_type(extracted_profile.model_dump())
extracted_profile = helper_handle_list_to_text(extracted_profile, cols=["hardskills", "softskills", "certifications", "business_domain_experiences"])
query = query_insert_profile_extracted.format(
fullname=extracted_profile['fullname'],
profile_id=profile_id,
high_edu_univ_1=extracted_profile['high_edu_univ_1'],
high_edu_major_1=extracted_profile['high_edu_major_1'],
high_edu_gpa_1=extracted_profile['high_edu_gpa_1'],
high_edu_univ_2=extracted_profile['high_edu_univ_2'],
high_edu_major_2=extracted_profile['high_edu_major_2'],
high_edu_gpa_2=extracted_profile['high_edu_gpa_2'],
high_edu_univ_3=extracted_profile['high_edu_univ_3'],
high_edu_major_3=extracted_profile['high_edu_major_3'],
high_edu_gpa_3=extracted_profile['high_edu_gpa_3'],
domicile=extracted_profile['domicile'],
yoe=extracted_profile['yoe'],
hardskills=extracted_profile['hardskills'],
softskills=extracted_profile['softskills'],
certifications=extracted_profile['certifications'],
business_domain_experiences=extracted_profile['business_domain_experiences']
)
await execute_query(query)
# check profile inserted
is_inserted = await fetch_data("select profile_id from cv_profile_extracted where profile_id = {profile_id}".format(profile_id=profile_id))
if is_inserted:
await update_raw_profile(profile_id=profile_id)
print(f"✅ Profile extracted and inserted for profile_id: {profile_id}")
else:
print(f"❌ Profile insertion failed for profile_id: {profile_id}")
except Exception as E:
failed_id.append({profile_id: str(E)})
print(f"❌ wrap_extract_profile error for profile_id: {profile_id}")
# data = asyncio.run(retrieve_raw_profiles_by_id(369))
# profile_id = data[0]["profile_id"]
# file_content = data[0]["file_content"]
# text = asyncio.run(pdf_reader(file_content))
# extracted_profile = asyncio.run(extract_profile(file_content))
# profile = asyncio.run(wrap_extract_profile(file=file_content, profile_id=profile_id))
# extracted_profile = sanitize_type(extracted_profile.model_dump())
# extracted_profile = helper_handle_list_to_text(extracted_profile, cols=["hardskills", "softskills", "certifications", "business_domain_experiences"])
async def KBProfileExtraction(batch_size: int = 10, failed_id: List = []):
try:
raw_profiles = await retrieve_raw_profiles(batch_size=batch_size, failed_id=failed_id)
tasks = []
for raw_profile in raw_profiles:
profile_id = raw_profile["profile_id"]
file_content = raw_profile["file_content"]
task = asyncio.create_task(wrap_extract_profile(file=file_content, profile_id=profile_id, failed_id=failed_id))
tasks.append(task)
extract_profiles = await asyncio.gather(*tasks)
return True
except Exception as E:
print(f"❌ Error extracting profile, {E}")
return False
async def run_rawingest_pipeline():
profile_id_raw = await fetch_data("select distinct profile_id from cv_raw;")
profile_id_raw = [f["profile_id"] for f in profile_id_raw]
profile_id_extracted = await fetch_data("select distinct profile_id from cv_profile_extracted;")
profile_id_extracted = [f["profile_id"] for f in profile_id_extracted]
profile_id_tobe_extracted = [p for p in profile_id_raw if p not in profile_id_extracted]
batch_size = 5
failed_id = []
nloops = (len(profile_id_tobe_extracted) // batch_size) + (1 if len(profile_id_tobe_extracted) % batch_size > 0 else 0)
for _ in range(nloops):
await KBProfileExtraction(batch_size=batch_size, failed_id=failed_id)
with open('failed_id.json', 'w') as fp:
json.dump({"failed_id": failed_id}, fp)
asyncio.run(run_rawingest_pipeline()) |