Spaces:
Sleeping
Sleeping
sonu sharma commited on
Commit ·
0a2a3e7
1
Parent(s): 3c2dc5c
deployment
Browse files- .dockerignore +22 -0
- .gitattributes +1 -35
- Dockerfile +68 -0
- app.py +244 -0
- data/candidate_embeddings.npy +3 -0
- data/candidate_ids.json +3 -0
- data/candidates.jsonl +3 -0
- data/sample_candidates.jsonl +3 -0
- pipeline/__init__.py +1 -0
- pipeline/config.py +75 -0
- pipeline/filters.py +119 -0
- pipeline/reasoning.py +198 -0
- pipeline/scoring.py +176 -0
- pipeline/text_builder.py +71 -0
- rank.py +251 -0
- requirements.txt +15 -0
- validate_submission.py +165 -0
.dockerignore
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
venv/
|
| 2 |
+
.git/
|
| 3 |
+
.gitattributes
|
| 4 |
+
*.pyc
|
| 5 |
+
__pycache__/
|
| 6 |
+
|
| 7 |
+
Dockerfile
|
| 8 |
+
.dockerignore
|
| 9 |
+
|
| 10 |
+
generate_sample.py
|
| 11 |
+
precompute_features.py
|
| 12 |
+
|
| 13 |
+
generated/
|
| 14 |
+
README.md
|
| 15 |
+
submission_metadata.yaml
|
| 16 |
+
banner.png
|
| 17 |
+
must_read/
|
| 18 |
+
|
| 19 |
+
# IDE / editor
|
| 20 |
+
.vscode/
|
| 21 |
+
.idea/
|
| 22 |
+
*.swp
|
.gitattributes
CHANGED
|
@@ -1,35 +1 @@
|
|
| 1 |
-
*
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
data/** filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dockerfile
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.13-slim
|
| 2 |
+
|
| 3 |
+
RUN apt-get update && \
|
| 4 |
+
apt-get install -y --no-install-recommends \
|
| 5 |
+
build-essential \
|
| 6 |
+
cmake && \
|
| 7 |
+
rm -rf /var/lib/apt/lists/*
|
| 8 |
+
|
| 9 |
+
WORKDIR /app
|
| 10 |
+
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
|
| 13 |
+
ENV CMAKE_BUILD_PARALLEL_LEVEL=2 \
|
| 14 |
+
MAKEFLAGS="-j2"
|
| 15 |
+
|
| 16 |
+
RUN pip install --no-cache-dir -r requirements.txt huggingface-hub
|
| 17 |
+
|
| 18 |
+
COPY . .
|
| 19 |
+
|
| 20 |
+
RUN python - <<'PY'
|
| 21 |
+
import os
|
| 22 |
+
from huggingface_hub import snapshot_download, hf_hub_download
|
| 23 |
+
from flashrank import Ranker
|
| 24 |
+
|
| 25 |
+
os.makedirs("weights", exist_ok=True)
|
| 26 |
+
|
| 27 |
+
print("Downloading BGE...")
|
| 28 |
+
snapshot_download(
|
| 29 |
+
repo_id="BAAI/bge-small-en-v1.5",
|
| 30 |
+
local_dir="weights/bge-small-en-v1.5",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
print("Downloading FlashRank...")
|
| 34 |
+
Ranker(
|
| 35 |
+
model_name="ms-marco-MiniLM-L-12-v2",
|
| 36 |
+
cache_dir="weights",
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
print("Downloading Llama...")
|
| 40 |
+
hf_hub_download(
|
| 41 |
+
repo_id="bartowski/Llama-3.2-1B-Instruct-GGUF",
|
| 42 |
+
filename="Llama-3.2-1B-Instruct-Q4_K_M.gguf",
|
| 43 |
+
local_dir="weights",
|
| 44 |
+
local_dir_use_symlinks=False,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
src = "weights/Llama-3.2-1B-Instruct-Q4_K_M.gguf"
|
| 48 |
+
dst = "weights/llama-3.2-1b-instruct-q4_k_m.gguf"
|
| 49 |
+
|
| 50 |
+
if os.path.exists(src):
|
| 51 |
+
os.rename(src, dst)
|
| 52 |
+
|
| 53 |
+
print("All weights downloaded.")
|
| 54 |
+
PY
|
| 55 |
+
|
| 56 |
+
RUN mkdir -p generated
|
| 57 |
+
|
| 58 |
+
ENV OMP_NUM_THREADS=2 \
|
| 59 |
+
OPENBLAS_NUM_THREADS=2 \
|
| 60 |
+
MKL_NUM_THREADS=2 \
|
| 61 |
+
TOKENIZERS_PARALLELISM=false \
|
| 62 |
+
PYTHONUNBUFFERED=1
|
| 63 |
+
|
| 64 |
+
RUN chmod +x run_sandbox.sh
|
| 65 |
+
|
| 66 |
+
EXPOSE 8501
|
| 67 |
+
|
| 68 |
+
ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
|
app.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import time
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import subprocess
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
st.set_page_config(
|
| 8 |
+
page_title="Candidate Ranking Pipeline",
|
| 9 |
+
layout="wide",
|
| 10 |
+
initial_sidebar_state="collapsed"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
st.markdown("""
|
| 14 |
+
<style>
|
| 15 |
+
.st-emotion-cache-b0dv7m {
|
| 16 |
+
background-color: #FF4B4B;
|
| 17 |
+
}
|
| 18 |
+
</style>
|
| 19 |
+
""", unsafe_allow_html=True)
|
| 20 |
+
|
| 21 |
+
if 'is_running' not in st.session_state:
|
| 22 |
+
st.session_state.is_running = False
|
| 23 |
+
if 'stopped' not in st.session_state:
|
| 24 |
+
st.session_state.stopped = False
|
| 25 |
+
if 'finished' not in st.session_state:
|
| 26 |
+
st.session_state.finished = False
|
| 27 |
+
if 'start_time' not in st.session_state:
|
| 28 |
+
st.session_state.start_time = 0.0
|
| 29 |
+
if 'elapsed_time' not in st.session_state:
|
| 30 |
+
st.session_state.elapsed_time = 0.0
|
| 31 |
+
|
| 32 |
+
def run_pipeline():
|
| 33 |
+
st.session_state.is_running = True
|
| 34 |
+
st.session_state.stopped = False
|
| 35 |
+
st.session_state.finished = False
|
| 36 |
+
st.session_state.start_time = time.time()
|
| 37 |
+
st.session_state.elapsed_time = 0.0
|
| 38 |
+
|
| 39 |
+
def stop_pipeline():
|
| 40 |
+
st.session_state.is_running = False
|
| 41 |
+
st.session_state.stopped = True
|
| 42 |
+
st.session_state.finished = False
|
| 43 |
+
if st.session_state.start_time > 0:
|
| 44 |
+
st.session_state.elapsed_time = time.time() - st.session_state.start_time
|
| 45 |
+
|
| 46 |
+
col_title, col_github = st.columns([10, 2])
|
| 47 |
+
with col_title:
|
| 48 |
+
st.title("🎯 Candidate Ranking Pipeline")
|
| 49 |
+
with col_github:
|
| 50 |
+
st.markdown("<div style='padding-top: 20px;'></div>", unsafe_allow_html=True)
|
| 51 |
+
st.link_button("🐙 View on GitHub", url="https://github.com/PushpakKumar12a/Candidate-Ranking", width='stretch')
|
| 52 |
+
|
| 53 |
+
col_left, col_right = st.columns([1.1, 2])
|
| 54 |
+
|
| 55 |
+
with col_left:
|
| 56 |
+
with st.container(border=True):
|
| 57 |
+
uploaded_file = st.file_uploader("File Uploading section")
|
| 58 |
+
with st.container(border=True):
|
| 59 |
+
use_sample = st.checkbox("Candidate Sample Data", value=True)
|
| 60 |
+
|
| 61 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 62 |
+
status_placeholder = st.empty()
|
| 63 |
+
progress_placeholder = st.empty()
|
| 64 |
+
timer_placeholder = st.empty()
|
| 65 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 66 |
+
|
| 67 |
+
if st.session_state.is_running:
|
| 68 |
+
with timer_placeholder:
|
| 69 |
+
st.iframe("""
|
| 70 |
+
<style>
|
| 71 |
+
body { margin: 0; padding: 0 }
|
| 72 |
+
#timer {font-family: sans-serif; font-size: 16px; font-weight: 600; }
|
| 73 |
+
</style>
|
| 74 |
+
<div id="timer">Elapsed Time: 0.0s</div>
|
| 75 |
+
<script>
|
| 76 |
+
const timerEl = document.getElementById('timer');
|
| 77 |
+
function syncTheme() {
|
| 78 |
+
try {
|
| 79 |
+
const parentColor = window.parent.getComputedStyle(window.parent.document.body).color;
|
| 80 |
+
if (parentColor) timerEl.style.color = parentColor;
|
| 81 |
+
} catch(e) {}
|
| 82 |
+
}
|
| 83 |
+
syncTheme();
|
| 84 |
+
setInterval(syncTheme, 1000);
|
| 85 |
+
|
| 86 |
+
const start = Date.now();
|
| 87 |
+
setInterval(() => {
|
| 88 |
+
const elapsed = ((Date.now() - start) / 1000).toFixed(1);
|
| 89 |
+
if (timerEl) {
|
| 90 |
+
timerEl.innerText = `Elapsed Time: ${elapsed}s`;
|
| 91 |
+
}
|
| 92 |
+
}, 100);
|
| 93 |
+
</script>
|
| 94 |
+
""",height=30)
|
| 95 |
+
elif st.session_state.elapsed_time > 0:
|
| 96 |
+
timer_placeholder.markdown(f'<div style="font-size:16px; font-weight:600; margin-bottom: 15px;">Elapsed Time: {st.session_state.elapsed_time:.1f}s</div>', unsafe_allow_html=True)
|
| 97 |
+
else:
|
| 98 |
+
timer_placeholder.markdown('<div style="font-size:16px; font-weight:600; margin-bottom: 15px;">Elapsed Time: 0.0s</div>', unsafe_allow_html=True)
|
| 99 |
+
|
| 100 |
+
btn_col1, btn_col2 = st.columns(2)
|
| 101 |
+
|
| 102 |
+
can_run = (uploaded_file is not None or use_sample) and not st.session_state.is_running
|
| 103 |
+
|
| 104 |
+
with btn_col1:
|
| 105 |
+
st.button("Run Pipeline", type="primary", width='stretch',
|
| 106 |
+
disabled=not can_run, on_click=run_pipeline)
|
| 107 |
+
with btn_col2:
|
| 108 |
+
st.button("Stop Pipeline", type="secondary", width='stretch',
|
| 109 |
+
disabled=not st.session_state.is_running, on_click=stop_pipeline)
|
| 110 |
+
|
| 111 |
+
st.markdown("""
|
| 112 |
+
<style>
|
| 113 |
+
.info-container {
|
| 114 |
+
height: 390px;
|
| 115 |
+
padding: 10px;
|
| 116 |
+
}
|
| 117 |
+
</style>
|
| 118 |
+
""", unsafe_allow_html=True)
|
| 119 |
+
|
| 120 |
+
with col_right:
|
| 121 |
+
with st.container(border=True):
|
| 122 |
+
st.subheader("⚙️ About the Pipeline flow")
|
| 123 |
+
st.markdown("""
|
| 124 |
+
> **This pipeline evaluates and ranks candidate profiles using a state-of-the-art, highly optimized 5-stage architecture designed for scale and precision:**
|
| 125 |
+
|
| 126 |
+
1. **Streaming & Filtering:** Ingests large-scale `JSON/JSONL` candidate data via memory-efficient streaming. Applies fast heuristic filters to instantly discard incomplete or unqualified profiles, drastically reducing memory overhead.
|
| 127 |
+
2. **Hybrid Retrieval:** Leverages a dual-encoder architecture. It combines sparse `BM25` lexical matching (for exact keyword extraction) with dense vector embeddings (e.g., `MiniLM`) to capture semantic meaning and contextual relevance, yielding a highly accurate initial shortlist.
|
| 128 |
+
3. **Candidate Profiling:** Performs a secondary pass to re-read the complete, rich data profiles exclusively for the shortlisted candidates. This isolates memory usage and prepares the deep textual features required for complex downstream analysis.
|
| 129 |
+
4. **Batch Reranking:** Applies advanced cross-encoder models via `FlashRank`. By executing the reranking in dynamically optimized batches, it computes highly precise query-document relevance scores without exhausting system resources.
|
| 130 |
+
5. **Scoring & Export:** Aggregates and normalizes the final compatibility scores, ranks the candidates in descending order of relevance, and generates a structured output CSV ready for immediate integration or human review.
|
| 131 |
+
""")
|
| 132 |
+
|
| 133 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 134 |
+
|
| 135 |
+
col_config = {
|
| 136 |
+
"candidate_id": st.column_config.TextColumn("candidate_id", width="small"),
|
| 137 |
+
"rank": st.column_config.NumberColumn("rank", width="small"),
|
| 138 |
+
"score": st.column_config.NumberColumn("score", width="small"),
|
| 139 |
+
"reasoning": st.column_config.TextColumn("reasoning", width="large")
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
preview_container = st.container(border=True)
|
| 143 |
+
with preview_container:
|
| 144 |
+
st.subheader("📊 CSV Preview Section")
|
| 145 |
+
df_placeholder = st.empty()
|
| 146 |
+
if not st.session_state.finished:
|
| 147 |
+
empty_df = pd.DataFrame(columns=["candidate_id", "rank", "score", "reasoning"])
|
| 148 |
+
df_placeholder.dataframe(empty_df, width='stretch', hide_index=True, column_config=col_config)
|
| 149 |
+
|
| 150 |
+
if st.session_state.stopped:
|
| 151 |
+
status_placeholder.warning("Pipeline was stopped.")
|
| 152 |
+
st.session_state.stopped = False
|
| 153 |
+
|
| 154 |
+
if st.session_state.is_running:
|
| 155 |
+
progress_bar = progress_placeholder.progress(0)
|
| 156 |
+
|
| 157 |
+
if uploaded_file is not None:
|
| 158 |
+
cands_path = "uploaded_candidates.jsonl"
|
| 159 |
+
with open(cands_path, "wb") as f:
|
| 160 |
+
f.write(uploaded_file.getvalue())
|
| 161 |
+
else:
|
| 162 |
+
cands_path = "data/sample_candidates.jsonl"
|
| 163 |
+
|
| 164 |
+
os.makedirs("generated", exist_ok=True)
|
| 165 |
+
out_csv = "generated/submission_nanopixel.csv"
|
| 166 |
+
|
| 167 |
+
process = subprocess.Popen(
|
| 168 |
+
["python", "rank.py", "--candidates", cands_path, "--out", out_csv],
|
| 169 |
+
stdout=subprocess.PIPE,
|
| 170 |
+
stderr=subprocess.STDOUT,
|
| 171 |
+
text=True,
|
| 172 |
+
bufsize=1
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
try:
|
| 176 |
+
for line in iter(process.stdout.readline, ''):
|
| 177 |
+
if not line:
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
if "[1/5]" in line:
|
| 181 |
+
status_placeholder.text("Stage 1/5: Streaming and filtering candidates...")
|
| 182 |
+
progress_bar.progress(10)
|
| 183 |
+
elif "[2/5]" in line:
|
| 184 |
+
status_placeholder.text("Stage 2/5: Hybrid Retrieval (BM25 + Dense Vectors)...")
|
| 185 |
+
progress_bar.progress(15)
|
| 186 |
+
elif "[3/5]" in line:
|
| 187 |
+
status_placeholder.text("Stage 3/5: Re-reading shortlisted candidates...")
|
| 188 |
+
progress_bar.progress(45)
|
| 189 |
+
elif "[4/5]" in line:
|
| 190 |
+
status_placeholder.text("Stage 4/5: FlashRank batch reranking...")
|
| 191 |
+
progress_bar.progress(80)
|
| 192 |
+
elif "[5/5]" in line:
|
| 193 |
+
status_placeholder.text("Stage 5/5: LLM reasoning & scoring...")
|
| 194 |
+
progress_bar.progress(85)
|
| 195 |
+
elif "Streamed and wrote" in line:
|
| 196 |
+
progress_bar.progress(100)
|
| 197 |
+
|
| 198 |
+
process.wait()
|
| 199 |
+
|
| 200 |
+
if process.returncode == 0:
|
| 201 |
+
st.session_state.is_running = False
|
| 202 |
+
st.session_state.finished = True
|
| 203 |
+
st.session_state.elapsed_time = time.time() - st.session_state.start_time
|
| 204 |
+
st.rerun()
|
| 205 |
+
else:
|
| 206 |
+
st.session_state.is_running = False
|
| 207 |
+
st.session_state.elapsed_time = time.time() - st.session_state.start_time
|
| 208 |
+
status_placeholder.error("Pipeline failed! Check terminal logs.")
|
| 209 |
+
st.rerun()
|
| 210 |
+
|
| 211 |
+
except BaseException as e:
|
| 212 |
+
if process.poll() is None:
|
| 213 |
+
process.kill()
|
| 214 |
+
raise e
|
| 215 |
+
|
| 216 |
+
if st.session_state.finished:
|
| 217 |
+
status_placeholder.success("Pipeline completed successfully!")
|
| 218 |
+
progress_placeholder.progress(100)
|
| 219 |
+
|
| 220 |
+
out_csv = "generated/submission_nanopixel.csv"
|
| 221 |
+
if os.path.exists(out_csv):
|
| 222 |
+
df = pd.read_csv(out_csv)
|
| 223 |
+
|
| 224 |
+
with preview_container:
|
| 225 |
+
csv_data = df.to_csv(index=False).encode('utf-8')
|
| 226 |
+
st.download_button(
|
| 227 |
+
label="Download Results",
|
| 228 |
+
data=csv_data,
|
| 229 |
+
file_name="submission_nanopixel.csv",
|
| 230 |
+
mime="text/csv",
|
| 231 |
+
type="primary"
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 235 |
+
|
| 236 |
+
df_placeholder.dataframe(
|
| 237 |
+
df,
|
| 238 |
+
width='stretch',
|
| 239 |
+
hide_index=True,
|
| 240 |
+
column_config=col_config
|
| 241 |
+
)
|
| 242 |
+
else:
|
| 243 |
+
with preview_container:
|
| 244 |
+
df_placeholder.error("Output CSV not found.")
|
data/candidate_embeddings.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:490a6c56d6ad89ad606ee2e2d8f69daca6edd06a4cd9b5d6e0a2f9d9b44ea98a
|
| 3 |
+
size 76800128
|
data/candidate_ids.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:65f4ebea2eb04711542e122579da76959635769e1550d92bc6e3e575b4dc8e3e
|
| 3 |
+
size 1600000
|
data/candidates.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:de7b8cae39a9f9378a2cd4f8153bfc1f84960bce0ae520f263423d129df4b335
|
| 3 |
+
size 487259903
|
data/sample_candidates.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:57ad7654b4bf0a1c7a7745235c1924d4e45be4170e2e0874d6a789344cba7af0
|
| 3 |
+
size 486558
|
pipeline/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Pipeline package for Redrob candidate ranking system.
|
pipeline/config.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
# Runtime
|
| 5 |
+
TODAY = date(2026, 6, 17)
|
| 6 |
+
INACTIVE_CUTOFF_DAYS = 180
|
| 7 |
+
MIN_RESPONSE_RATE = 0.10
|
| 8 |
+
BM25_TOP_K = 500
|
| 9 |
+
FINAL_TOP_K = 100
|
| 10 |
+
FLASHRANK_BATCH_SIZE = 128
|
| 11 |
+
PROJECT_DIR = Path(__file__).resolve().parent.parent
|
| 12 |
+
MAX_TEXT_BM25 = 600
|
| 13 |
+
MAX_TEXT_RERANK = 1024
|
| 14 |
+
|
| 15 |
+
# JD queries
|
| 16 |
+
JD_BM25 = (
|
| 17 |
+
"Senior AI Engineer machine learning embeddings retrieval ranking "
|
| 18 |
+
"LLM fine-tuning production Python vector database search "
|
| 19 |
+
"sentence-transformers FAISS Pinecone Weaviate Qdrant Elasticsearch "
|
| 20 |
+
"hybrid search semantic search NLP information retrieval recommendation "
|
| 21 |
+
"NDCG MRR MAP deep learning PyTorch TensorFlow transformer BERT "
|
| 22 |
+
"applied ML product company startup LoRA QLoRA PEFT MLOps "
|
| 23 |
+
"ranking system learning to rank XGBoost FastAPI Docker Kubernetes"
|
| 24 |
+
)
|
| 25 |
+
JD_SEMANTIC = (
|
| 26 |
+
"Senior AI Engineer for founding team at Redrob AI, Series A "
|
| 27 |
+
"talent intelligence platform in Pune/Noida India. 5-9 years "
|
| 28 |
+
"experience in embeddings, retrieval, ranking, LLMs. Must have "
|
| 29 |
+
"production embeddings-based retrieval (sentence-transformers, BGE, E5), "
|
| 30 |
+
"vector databases (Pinecone, Weaviate, Qdrant, FAISS, Elasticsearch), "
|
| 31 |
+
"strong Python, evaluation frameworks (NDCG, MRR, MAP). "
|
| 32 |
+
"Nice-to-have: LLM fine-tuning, learning-to-rank, HR-tech. "
|
| 33 |
+
"Not suitable: pure consulting, CV/speech/robotics only, no production."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Lookup data
|
| 37 |
+
CORE_SKILLS = {
|
| 38 |
+
"sentence-transformers", "embeddings", "semantic search", "vector search",
|
| 39 |
+
"faiss", "pinecone", "weaviate", "qdrant", "milvus", "elasticsearch",
|
| 40 |
+
"opensearch", "hybrid search", "information retrieval", "vector database",
|
| 41 |
+
"nlp", "natural language processing", "transformers", "bert", "gpt",
|
| 42 |
+
"machine learning", "deep learning", "neural networks",
|
| 43 |
+
"pytorch", "tensorflow", "scikit-learn",
|
| 44 |
+
"llm", "large language models", "fine-tuning", "fine-tuning llms",
|
| 45 |
+
"lora", "qlora", "peft", "prompt engineering", "rag",
|
| 46 |
+
"retrieval augmented generation",
|
| 47 |
+
"search", "ranking", "recommendation systems", "learning to rank",
|
| 48 |
+
"bm25", "tf-idf", "recommendation engine",
|
| 49 |
+
"python", "rest api", "fastapi", "flask", "docker", "kubernetes",
|
| 50 |
+
"mlops", "aws", "gcp", "azure", "sql", "spark", "airflow",
|
| 51 |
+
}
|
| 52 |
+
CONSULTING_FIRMS = {
|
| 53 |
+
"tcs", "tata consultancy services", "infosys", "wipro", "accenture",
|
| 54 |
+
"cognizant", "capgemini", "hcl", "hcl technologies", "tech mahindra",
|
| 55 |
+
"mindtree", "mphasis", "ltimindtree", "cts",
|
| 56 |
+
}
|
| 57 |
+
LOC_PRI = {"pune", "noida"}
|
| 58 |
+
LOC_SEC = {
|
| 59 |
+
"hyderabad", "mumbai", "delhi", "delhi ncr", "bengaluru",
|
| 60 |
+
"bangalore", "gurgaon", "gurugram", "new delhi", "chennai",
|
| 61 |
+
}
|
| 62 |
+
TITLE_TIERS = {
|
| 63 |
+
"strong": (["ai engineer", "ml engineer", "machine learning engineer",
|
| 64 |
+
"nlp engineer", "search engineer", "ranking engineer",
|
| 65 |
+
"applied scientist", "research engineer", "deep learning engineer",
|
| 66 |
+
"senior ai", "staff ai", "lead ai", "senior ml", "staff ml", "lead ml"], 1.15),
|
| 67 |
+
"moderate": (["data scientist", "software engineer", "backend engineer",
|
| 68 |
+
"full stack", "platform engineer", "senior software",
|
| 69 |
+
"staff engineer", "tech lead", "data engineer", "analytics engineer"], 1.02),
|
| 70 |
+
"red_flag": (["hr manager", "accountant", "sales executive", "marketing manager",
|
| 71 |
+
"content writer", "graphic designer", "operations manager",
|
| 72 |
+
"project manager", "customer support", "business analyst",
|
| 73 |
+
"civil engineer", "mechanical engineer", "electrical engineer"], 0.50),
|
| 74 |
+
}
|
| 75 |
+
TITLE_DEFAULT_MULT = 0.85
|
pipeline/filters.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from .config import TODAY, INACTIVE_CUTOFF_DAYS, MIN_RESPONSE_RATE
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def parse_date(date_string):
|
| 6 |
+
if not date_string:
|
| 7 |
+
return None
|
| 8 |
+
try:
|
| 9 |
+
return datetime.strptime(date_string, "%Y-%m-%d").date()
|
| 10 |
+
except (ValueError, TypeError):
|
| 11 |
+
return None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def days_since(date_value):
|
| 15 |
+
if date_value:
|
| 16 |
+
return (TODAY - date_value).days
|
| 17 |
+
return 9999
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def check_zero_exp_advanced(skills, career, years):
|
| 21 |
+
if years != 0:
|
| 22 |
+
return False
|
| 23 |
+
count = 0
|
| 24 |
+
for skill in skills:
|
| 25 |
+
if skill.get("proficiency") in ("expert", "advanced"):
|
| 26 |
+
count += 1
|
| 27 |
+
return count >= 3
|
| 28 |
+
|
| 29 |
+
def check_zero_duration_experts(skills, career, years):
|
| 30 |
+
count = 0
|
| 31 |
+
for skill in skills:
|
| 32 |
+
if skill.get("proficiency") == "expert" and skill.get("duration_months", 0) == 0:
|
| 33 |
+
count += 1
|
| 34 |
+
return count >= 3
|
| 35 |
+
|
| 36 |
+
def check_too_many_experts(skills, career, years):
|
| 37 |
+
count = 0
|
| 38 |
+
for skill in skills:
|
| 39 |
+
if skill.get("proficiency") == "expert":
|
| 40 |
+
count += 1
|
| 41 |
+
return count >= 8 and years < 5
|
| 42 |
+
|
| 43 |
+
def check_career_overflow(skills, career, years):
|
| 44 |
+
if years <= 0:
|
| 45 |
+
return False
|
| 46 |
+
total_months = 0
|
| 47 |
+
for job in career:
|
| 48 |
+
total_months += job.get("duration_months", 0)
|
| 49 |
+
return total_months > years * 24
|
| 50 |
+
|
| 51 |
+
def check_role_overflow(skills, career, years):
|
| 52 |
+
if years <= 0:
|
| 53 |
+
return False
|
| 54 |
+
max_allowed = years * 12 + 18
|
| 55 |
+
for job in career:
|
| 56 |
+
if job.get("duration_months", 0) > max_allowed:
|
| 57 |
+
return True
|
| 58 |
+
return False
|
| 59 |
+
|
| 60 |
+
def check_broad_expertise(skills, career, years):
|
| 61 |
+
count = 0
|
| 62 |
+
for skill in skills:
|
| 63 |
+
if skill.get("proficiency") == "expert":
|
| 64 |
+
count += 1
|
| 65 |
+
return count >= 10
|
| 66 |
+
|
| 67 |
+
def check_zero_endorsements(skills, career, years):
|
| 68 |
+
count = 0
|
| 69 |
+
for skill in skills:
|
| 70 |
+
if skill.get("proficiency") == "expert" and skill.get("endorsements", 0) == 0:
|
| 71 |
+
count += 1
|
| 72 |
+
return count >= 5
|
| 73 |
+
|
| 74 |
+
def check_ghost_responder(candidate):
|
| 75 |
+
signals = candidate.get("redrob_signals", {})
|
| 76 |
+
return signals.get("recruiter_response_rate", 0) > 0 and signals.get("profile_views_received_30d", 0) == 0 and signals.get("search_appearance_30d", 0) == 0
|
| 77 |
+
|
| 78 |
+
def check_skill_duration_overflow(candidate):
|
| 79 |
+
skills = candidate.get("skills", [])
|
| 80 |
+
years_exp = candidate.get("profile", {}).get("years_of_experience", 0)
|
| 81 |
+
max_skill_dur = max([s.get("duration_months", 0) for s in skills] + [0])
|
| 82 |
+
return max_skill_dur > years_exp * 12 + 60
|
| 83 |
+
|
| 84 |
+
HONEYPOT_RULES = [
|
| 85 |
+
(check_zero_exp_advanced, 3),
|
| 86 |
+
(check_zero_duration_experts, 3),
|
| 87 |
+
(check_too_many_experts, 2),
|
| 88 |
+
(check_career_overflow, 2),
|
| 89 |
+
(check_role_overflow, 2),
|
| 90 |
+
(check_broad_expertise, 2),
|
| 91 |
+
(check_zero_endorsements, 2),
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def is_honeypot(candidate):
|
| 96 |
+
skills = candidate.get("skills", [])
|
| 97 |
+
career = candidate.get("career_history", [])
|
| 98 |
+
years = candidate.get("profile", {}).get("years_of_experience", 0)
|
| 99 |
+
total_score = 0
|
| 100 |
+
for check_fn, weight in HONEYPOT_RULES:
|
| 101 |
+
try:
|
| 102 |
+
if check_fn(skills, career, years):
|
| 103 |
+
total_score += weight
|
| 104 |
+
except TypeError:
|
| 105 |
+
if check_fn(candidate):
|
| 106 |
+
total_score += weight
|
| 107 |
+
|
| 108 |
+
if check_ghost_responder(candidate):
|
| 109 |
+
total_score += 2
|
| 110 |
+
if check_skill_duration_overflow(candidate):
|
| 111 |
+
total_score += 2
|
| 112 |
+
|
| 113 |
+
return total_score >= 2
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def passes_prefilter(candidate):
|
| 117 |
+
if is_honeypot(candidate):
|
| 118 |
+
return False
|
| 119 |
+
return True
|
pipeline/reasoning.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import re
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Pre defined core skills
|
| 6 |
+
AI_KEYWORDS = {
|
| 7 |
+
"llm", "rag", "pytorch", "embeddings", "pinecone", "fine-tuning",
|
| 8 |
+
"machine learning", "nlp", "genai", "python", "fastapi", "docker",
|
| 9 |
+
"tensorflow", "keras", "scikit-learn", "lstm", "naive bayes",
|
| 10 |
+
"computer vision", "cnn", "transformers", "langchain", "llamaindex",
|
| 11 |
+
"huggingface", "prompt engineering", "faiss", "milvus", "weaviate",
|
| 12 |
+
"pandas", "numpy", "sql", "aws", "kubernetes", "docker compose",
|
| 13 |
+
"mlflow", "airflow", "django", "flask", "node.js", "express",
|
| 14 |
+
"react", "rest api", "qlora", "diffusion models", "data science",
|
| 15 |
+
"deep learning", "predictive modeling", "sentiment analysis"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# LLM Singleton
|
| 19 |
+
llm = None
|
| 20 |
+
|
| 21 |
+
def get_llm():
|
| 22 |
+
global llm
|
| 23 |
+
if llm is None:
|
| 24 |
+
from llama_cpp import Llama
|
| 25 |
+
from .config import PROJECT_DIR
|
| 26 |
+
|
| 27 |
+
llm = Llama(
|
| 28 |
+
model_path=str(PROJECT_DIR / "weights" / "llama-3.2-1b-instruct-q4_k_m.gguf"),
|
| 29 |
+
n_ctx=512,
|
| 30 |
+
n_threads=int(os.environ.get("OMP_NUM_THREADS", "4")),
|
| 31 |
+
n_batch=256,
|
| 32 |
+
verbose=False
|
| 33 |
+
)
|
| 34 |
+
return llm
|
| 35 |
+
|
| 36 |
+
# Data Extraction & HR logic
|
| 37 |
+
def extract_candidate_facts(candidate):
|
| 38 |
+
profile = candidate.get("profile", {})
|
| 39 |
+
signals = candidate.get("redrob_signals", {})
|
| 40 |
+
|
| 41 |
+
title = profile.get("current_title", "Tech Professional")
|
| 42 |
+
exp = profile.get("years_of_experience", 0)
|
| 43 |
+
|
| 44 |
+
skills_list = [s.get("name") for s in candidate.get("skills", [])]
|
| 45 |
+
core_skills = [s for s in skills_list if s.lower() in AI_KEYWORDS][:3]
|
| 46 |
+
if not core_skills:
|
| 47 |
+
core_skills = skills_list[:2]
|
| 48 |
+
skills_str = ", ".join(core_skills) if core_skills else "general tools"
|
| 49 |
+
|
| 50 |
+
notice = signals.get("notice_period_days", 30)
|
| 51 |
+
industry = profile.get("current_industry", "general tech")
|
| 52 |
+
|
| 53 |
+
is_immediate = "eligible for immediate hiring" if notice <= 15 else "not eligible for immediate start"
|
| 54 |
+
|
| 55 |
+
if exp < 5:
|
| 56 |
+
exp_gap = "lacks the required senior-level experience"
|
| 57 |
+
elif exp > 10:
|
| 58 |
+
exp_gap = "may be over-experienced for a founding team pace"
|
| 59 |
+
elif not core_skills:
|
| 60 |
+
exp_gap = "lacks direct hands-on exposure to core AI tech"
|
| 61 |
+
else:
|
| 62 |
+
exp_gap = "shows appropriate tenure"
|
| 63 |
+
|
| 64 |
+
return title, exp, skills_str, notice, is_immediate, exp_gap, industry
|
| 65 |
+
|
| 66 |
+
# 10-tier tone generator
|
| 67 |
+
def get_tone_instruction(rank):
|
| 68 |
+
|
| 69 |
+
if rank <= 10:
|
| 70 |
+
return "Tone Profile (Ranks 1-10): Exceptionally positive. Frame the candidate as an elite, top-tier fit with deep alignment to complex AI systems."
|
| 71 |
+
elif rank <= 20:
|
| 72 |
+
return "Tone Profile (Ranks 11-20): Very strong. Highlight robust technical depth and solid foundational fit, noting them as highly capable."
|
| 73 |
+
elif rank <= 30:
|
| 74 |
+
return "Tone Profile (Ranks 21-30): Solid and reliable. Focus on their dependable experience and good general alignment."
|
| 75 |
+
elif rank <= 40:
|
| 76 |
+
return "Tone Profile (Ranks 31-40): Competent but standard. Note decent baseline skills, but hint at a lack of exceptional standout traits."
|
| 77 |
+
elif rank <= 50:
|
| 78 |
+
return "Tone Profile (Ranks 41-50): Borderline/Average. Frame the experience as acceptable but somewhat generic or overly broad."
|
| 79 |
+
elif rank <= 60:
|
| 80 |
+
return "Tone Profile (Ranks 51-60): Mediocre. Subtly emphasize noticeable gaps in scale, specific production alignment, or trajectory."
|
| 81 |
+
elif rank <= 70:
|
| 82 |
+
return "Tone Profile (Ranks 61-70): Weak fit. Highlight misalignment in industry, tooling focus, or required tenure."
|
| 83 |
+
elif rank <= 80:
|
| 84 |
+
return "Tone Profile (Ranks 71-80): Poor fit. Express clear concern over their tech stack relevance, background, or behavioral signals."
|
| 85 |
+
elif rank <= 90:
|
| 86 |
+
return "Tone Profile (Ranks 81-90): Highly questionable. Frame as a distinct mismatch for this fast-paced startup role, noting significant flaws."
|
| 87 |
+
else:
|
| 88 |
+
return "Tone Profile (Ranks 91-100): Complete mismatch. Explicitly highlight fatal flaws, irrelevant backgrounds (e.g., non-engineering), or disqualifying traits."
|
| 89 |
+
|
| 90 |
+
# Dynamic prompt builder
|
| 91 |
+
def get_hr_prompt(rank, title, exp, skills, notice, is_immediate, exp_gap, industry):
|
| 92 |
+
tone = get_tone_instruction(rank)
|
| 93 |
+
|
| 94 |
+
sys_msg = f"""You are an objective but discerning HR analyst evaluating candidates. Draft a crisp, 2-sentence summary of the candidate.
|
| 95 |
+
Your response MUST strictly follow this exact flow and be exactly between 30 and 40 words:
|
| 96 |
+
Sentence 1: State the last title, years of experience, key skills, and industry.
|
| 97 |
+
Sentence 2: State the experience status, and end the sentence strictly with the notice period and immediate hiring eligibility.
|
| 98 |
+
|
| 99 |
+
CRITICAL RULES:
|
| 100 |
+
- {tone} Incorporate this tone into your word choices naturally without sounding robotic.
|
| 101 |
+
- Vary your sentence starters: Use "The candidate" for one sentence, and the job title (e.g., "The AI Engineer") for the other.
|
| 102 |
+
- Do NOT start any sentence with a pronoun (He, She, They). You may use singular pronouns (his, her) in the middle of sentences.
|
| 103 |
+
- Avoid using "they" or "their" since the candidate is singular. Ensure proper singular verb agreement.
|
| 104 |
+
- NO standalone conclusions (e.g., do not add "This makes them a good fit" at the very end).
|
| 105 |
+
- End the text immediately after stating the notice period.
|
| 106 |
+
- Write in neutral third person. Do not use "we", "our", or "us".
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
prompt = f"""<|start_header_id|>system<|end_header_id|>
|
| 110 |
+
{sys_msg} Output ONLY the final reasoning text.<|eot_id|><|start_header_id|>user<|end_header_id|>
|
| 111 |
+
Title: {title}
|
| 112 |
+
Experience: {exp} years
|
| 113 |
+
Skills: {skills}
|
| 114 |
+
Industry: {industry}
|
| 115 |
+
Experience Note: {exp_gap}
|
| 116 |
+
Notice Period: {notice} days ({is_immediate})
|
| 117 |
+
<|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
return prompt
|
| 121 |
+
|
| 122 |
+
# Output Cleanser
|
| 123 |
+
def enforce_sentence_limit(text):
|
| 124 |
+
text = re.sub(r'(?i)^(here is( the)?.*?:|based on.*?:|title:\s*|experience:\s*)', '', text).strip()
|
| 125 |
+
text = re.sub(r'(?i)^our (team|company) (is seeking|seeks to hire|has hired|seeks) (for )?(a|an|the )?', '', text).strip()
|
| 126 |
+
|
| 127 |
+
replacements = {
|
| 128 |
+
r'\b(?:i|they)\b': 'the candidate',
|
| 129 |
+
r'\b(?:my|their)\b': "the candidate's",
|
| 130 |
+
r'\b(?:we)\b': 'the organization',
|
| 131 |
+
r'\b(?:our)\b': "the organization's",
|
| 132 |
+
r'\b(?:you)\b': 'the candidate',
|
| 133 |
+
r'\b(?:your)\b': "the candidate's",
|
| 134 |
+
r'\b(?:John Doe|John|Johnson|Ms\. Smith|Mr\. Smith|Smith)\b': 'the candidate'
|
| 135 |
+
}
|
| 136 |
+
for pattern, replacement in replacements.items():
|
| 137 |
+
text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)
|
| 138 |
+
|
| 139 |
+
verb_fixes = {
|
| 140 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+are\b': r'\1 is',
|
| 141 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+have\b': r'\1 has',
|
| 142 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+were\b': r'\1 was',
|
| 143 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+do\b': r'\1 does',
|
| 144 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+lack\b': r'\1 lacks',
|
| 145 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+hold\b': r'\1 holds',
|
| 146 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+possess\b': r'\1 possesses',
|
| 147 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+show\b': r'\1 shows',
|
| 148 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+demonstrate\b': r'\1 demonstrates',
|
| 149 |
+
r'(?i)\b(the candidate|the candidate\'s)\s+need\b': r'\1 needs'
|
| 150 |
+
}
|
| 151 |
+
for pattern, replacement in verb_fixes.items():
|
| 152 |
+
text = re.sub(pattern, replacement, text)
|
| 153 |
+
|
| 154 |
+
text = re.sub(r'[\n\r]+', ' ', text)
|
| 155 |
+
text = text.replace('"', '').replace("'", "").strip()
|
| 156 |
+
|
| 157 |
+
sentences = re.split(r'(?<=[.!?])\s+(?=[A-Z])', text)
|
| 158 |
+
valid_sentences = [s.strip() for s in sentences if len(s.strip()) > 3]
|
| 159 |
+
|
| 160 |
+
# Target only subjective conclusions
|
| 161 |
+
fluff_pattern = re.compile(r'(?i)[,\s]*(making the candidate|thus|therefore|which aligns|suggesting|highlighting|demonstrating|showcasing|meaning|resulting in|indicating a good fit).*$')
|
| 162 |
+
|
| 163 |
+
processed_sentences = []
|
| 164 |
+
for s in valid_sentences[:2]:
|
| 165 |
+
s = fluff_pattern.sub('', s)
|
| 166 |
+
|
| 167 |
+
# Enforce no pronouns at the very start of the sentence
|
| 168 |
+
s = re.sub(r'^(He|She|It)\b\s*', 'The candidate ', s, flags=re.IGNORECASE)
|
| 169 |
+
|
| 170 |
+
if s:
|
| 171 |
+
s = s[0].upper() + s[1:]
|
| 172 |
+
processed_sentences.append(s)
|
| 173 |
+
|
| 174 |
+
final_text = " ".join(processed_sentences).strip()
|
| 175 |
+
|
| 176 |
+
if final_text and not final_text.endswith(('.', '!', '?')):
|
| 177 |
+
final_text = re.sub(r'[,;:\-]\s*$', '', final_text) + '.'
|
| 178 |
+
|
| 179 |
+
return final_text
|
| 180 |
+
|
| 181 |
+
# Top level export
|
| 182 |
+
def generate_reasoning(candidate, rank):
|
| 183 |
+
title, exp, skills, notice, is_immediate, exp_gap, industry = extract_candidate_facts(candidate)
|
| 184 |
+
prompt = get_hr_prompt(rank, title, exp, skills, notice, is_immediate, exp_gap, industry)
|
| 185 |
+
|
| 186 |
+
llm = get_llm()
|
| 187 |
+
|
| 188 |
+
response = llm(
|
| 189 |
+
prompt,
|
| 190 |
+
max_tokens=90,
|
| 191 |
+
temperature=0.65,
|
| 192 |
+
top_p=0.92,
|
| 193 |
+
repeat_penalty=1.15,
|
| 194 |
+
stop=["<|eot_id|>"]
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
raw_text = response['choices'][0]['text'].strip()
|
| 198 |
+
return enforce_sentence_limit(raw_text)
|
pipeline/scoring.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from .config import (
|
| 4 |
+
CONSULTING_FIRMS, LOC_PRI, LOC_SEC,
|
| 5 |
+
TITLE_TIERS, TITLE_DEFAULT_MULT,
|
| 6 |
+
)
|
| 7 |
+
from .filters import parse_date, days_since
|
| 8 |
+
|
| 9 |
+
# Threshold tables as Numpy arrays
|
| 10 |
+
TABLES = {
|
| 11 |
+
"exp": (np.array([3, 4, 5, 9, 12, 15]), np.array([0.78, 0.92, 1.00, 1.08, 1.00, 0.92, 0.78])),
|
| 12 |
+
"notice": (np.array([30, 60, 90]), np.array([1.04, 0.97, 0.90, 0.82])),
|
| 13 |
+
"rr": (np.array([0.06, 0.20, 0.40, 0.60]), np.array([0.10, 0.92, 0.97, 1.02, 1.05])),
|
| 14 |
+
"recency": (np.array([14, 45, 90, 179]), np.array([1.05, 1.02, 0.98, 0.93, 0.10])),
|
| 15 |
+
"github": (np.array([20, 50]), np.array([1.00, 1.02, 1.05])),
|
| 16 |
+
"profile": (np.array([70, 85]), np.array([0.95, 1.00, 1.03])),
|
| 17 |
+
"avg_resp": (np.array([2, 12, 24, 48]), np.array([1.05, 1.00, 0.95, 0.90, 0.85])),
|
| 18 |
+
"views": (np.array([10, 50, 100]), np.array([0.95, 1.00, 1.02, 1.05])),
|
| 19 |
+
"apps": (np.array([5, 20, 50]), np.array([0.98, 1.00, 1.02, 1.00])),
|
| 20 |
+
"assess": (np.array([60, 80, 95]), np.array([0.95, 1.00, 1.03, 1.06])),
|
| 21 |
+
"conn": (np.array([50, 200, 500]), np.array([0.95, 1.00, 1.02, 1.05])),
|
| 22 |
+
"endors": (np.array([5, 20, 50]), np.array([0.98, 1.00, 1.02, 1.05])),
|
| 23 |
+
"search": (np.array([5, 20, 50]), np.array([0.95, 1.00, 1.02, 1.04])),
|
| 24 |
+
"saved": (np.array([1, 5, 10]), np.array([0.98, 1.00, 1.03, 1.06])),
|
| 25 |
+
"int_rate": (np.array([0.5, 0.8, 0.95]), np.array([0.85, 0.95, 1.00, 1.05])),
|
| 26 |
+
"offer_rate": (np.array([0.3, 0.7, 0.9]), np.array([0.90, 0.98, 1.02, 1.05])),
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
# Numpy searchsorted threshold lookup.
|
| 30 |
+
def step_lookup(value, table_key):
|
| 31 |
+
breakpoints, values = TABLES[table_key]
|
| 32 |
+
index = np.searchsorted(breakpoints, value, side="right")
|
| 33 |
+
return float(values[index])
|
| 34 |
+
|
| 35 |
+
# Returns multiplier based on job title using keywords.
|
| 36 |
+
def title_multiplier(title_lower):
|
| 37 |
+
for tier_name, (keywords, multiplier) in TITLE_TIERS.items():
|
| 38 |
+
for keyword in keywords:
|
| 39 |
+
if keyword in title_lower:
|
| 40 |
+
return multiplier
|
| 41 |
+
return TITLE_DEFAULT_MULT
|
| 42 |
+
|
| 43 |
+
# Returns multiplier based on location.
|
| 44 |
+
def location_multiplier(location, country, willing_to_relocate):
|
| 45 |
+
for loc in LOC_PRI:
|
| 46 |
+
if loc in location:
|
| 47 |
+
return 1.08
|
| 48 |
+
for loc in LOC_SEC:
|
| 49 |
+
if loc in location:
|
| 50 |
+
return 1.04
|
| 51 |
+
if "india" in country:
|
| 52 |
+
if willing_to_relocate:
|
| 53 |
+
return 1.00
|
| 54 |
+
return 0.92
|
| 55 |
+
if willing_to_relocate:
|
| 56 |
+
return 0.88
|
| 57 |
+
return 0.78
|
| 58 |
+
|
| 59 |
+
# Returns multiplier based on whether candidate has worked in consulting firms.
|
| 60 |
+
def consulting_multiplier(career_history):
|
| 61 |
+
if not career_history:
|
| 62 |
+
return 1.0
|
| 63 |
+
for job in career_history:
|
| 64 |
+
company_name = job.get("company", "").lower()
|
| 65 |
+
is_consulting = False
|
| 66 |
+
for firm in CONSULTING_FIRMS:
|
| 67 |
+
if firm in company_name:
|
| 68 |
+
is_consulting = True
|
| 69 |
+
break
|
| 70 |
+
if not is_consulting:
|
| 71 |
+
return 1.0
|
| 72 |
+
return 0.65
|
| 73 |
+
|
| 74 |
+
# Returns multiplier based on verification signals.
|
| 75 |
+
def verification_multiplier(signals):
|
| 76 |
+
verified_count = 0
|
| 77 |
+
if signals.get("verified_email", False):
|
| 78 |
+
verified_count += 1
|
| 79 |
+
if signals.get("verified_phone", False):
|
| 80 |
+
verified_count += 1
|
| 81 |
+
if signals.get("linkedin_connected", False):
|
| 82 |
+
verified_count += 1
|
| 83 |
+
lookup = [0.95, 1.0, 1.0, 1.03]
|
| 84 |
+
return lookup[verified_count]
|
| 85 |
+
|
| 86 |
+
# Returns multiplier based on signup date.
|
| 87 |
+
def loyalty_multiplier(signup_date_str):
|
| 88 |
+
if not signup_date_str: return 1.0
|
| 89 |
+
days = days_since(parse_date(signup_date_str))
|
| 90 |
+
if days > 1000: return 1.05
|
| 91 |
+
if days > 365: return 1.02
|
| 92 |
+
return 1.0
|
| 93 |
+
|
| 94 |
+
# Returns multiplier based on expected salary range.
|
| 95 |
+
def salary_multiplier(salary_dict):
|
| 96 |
+
if not salary_dict: return 1.0
|
| 97 |
+
s_min = salary_dict.get("min", 0)
|
| 98 |
+
if s_min > 50: return 0.85
|
| 99 |
+
if s_min > 35: return 0.95
|
| 100 |
+
return 1.0
|
| 101 |
+
|
| 102 |
+
# Returns multiplier based on work mode.
|
| 103 |
+
def work_mode_multiplier(mode):
|
| 104 |
+
mode = (mode or "").lower()
|
| 105 |
+
if mode in ["onsite", "hybrid", "flexible"]: return 1.05
|
| 106 |
+
if mode == "remote": return 0.95
|
| 107 |
+
return 1.0
|
| 108 |
+
|
| 109 |
+
# Returns multiplier based on candidate behavior.
|
| 110 |
+
def behavioral_multiplier(candidate):
|
| 111 |
+
profile = candidate.get("profile", {})
|
| 112 |
+
signals = candidate.get("redrob_signals", {})
|
| 113 |
+
career_history = candidate.get("career_history", [])
|
| 114 |
+
|
| 115 |
+
# 1. last_active_date
|
| 116 |
+
last_active_date = signals.get("last_active_date")
|
| 117 |
+
recency_days = days_since(parse_date(last_active_date))
|
| 118 |
+
|
| 119 |
+
# 2. open_to_work_flag
|
| 120 |
+
open_to_work_mult = 1.04 if signals.get("open_to_work_flag") else 0.96
|
| 121 |
+
|
| 122 |
+
# 3. offer_acceptance_rate
|
| 123 |
+
offer_rate_val = signals.get("offer_acceptance_rate", -1)
|
| 124 |
+
offer_mult = 1.0 if offer_rate_val < 0 else step_lookup(offer_rate_val, "offer_rate")
|
| 125 |
+
|
| 126 |
+
# 4. skill_assessment_scores
|
| 127 |
+
assess_dict = signals.get("skill_assessment_scores", {})
|
| 128 |
+
if assess_dict:
|
| 129 |
+
avg_score = sum(assess_dict.values()) / len(assess_dict)
|
| 130 |
+
else:
|
| 131 |
+
avg_score = 70
|
| 132 |
+
assess_mult = step_lookup(avg_score, "assess")
|
| 133 |
+
|
| 134 |
+
factors = np.array([
|
| 135 |
+
# Base multipliers
|
| 136 |
+
step_lookup(profile.get("years_of_experience", 0), "exp"),
|
| 137 |
+
title_multiplier(profile.get("current_title", "").lower()),
|
| 138 |
+
location_multiplier(
|
| 139 |
+
profile.get("location", "").lower(),
|
| 140 |
+
profile.get("country", "").lower(),
|
| 141 |
+
signals.get("willing_to_relocate", False),
|
| 142 |
+
),
|
| 143 |
+
consulting_multiplier(career_history),
|
| 144 |
+
|
| 145 |
+
# Redrob signals
|
| 146 |
+
step_lookup(signals.get("notice_period_days", 30), "notice"),
|
| 147 |
+
step_lookup(signals.get("recruiter_response_rate", 0.5), "rr"),
|
| 148 |
+
step_lookup(recency_days, "recency"),
|
| 149 |
+
open_to_work_mult,
|
| 150 |
+
step_lookup(signals.get("github_activity_score", -1), "github"),
|
| 151 |
+
step_lookup(signals.get("profile_completeness_score", 50), "profile"),
|
| 152 |
+
verification_multiplier(signals),
|
| 153 |
+
|
| 154 |
+
loyalty_multiplier(signals.get("signup_date")),
|
| 155 |
+
step_lookup(signals.get("profile_views_received_30d", 0), "views"),
|
| 156 |
+
step_lookup(signals.get("applications_submitted_30d", 0), "apps"),
|
| 157 |
+
step_lookup(signals.get("avg_response_time_hours", 24), "avg_resp"),
|
| 158 |
+
assess_mult,
|
| 159 |
+
step_lookup(signals.get("connection_count", 0), "conn"),
|
| 160 |
+
step_lookup(signals.get("endorsements_received", 0), "endors"),
|
| 161 |
+
salary_multiplier(signals.get("expected_salary_range_inr_lpa")),
|
| 162 |
+
work_mode_multiplier(signals.get("preferred_work_mode")),
|
| 163 |
+
step_lookup(signals.get("search_appearance_30d", 0), "search"),
|
| 164 |
+
step_lookup(signals.get("saved_by_recruiters_30d", 0), "saved"),
|
| 165 |
+
step_lookup(signals.get("interview_completion_rate", 1.0), "int_rate"),
|
| 166 |
+
offer_mult,
|
| 167 |
+
], dtype=np.float16)
|
| 168 |
+
|
| 169 |
+
return float(np.prod(factors))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def rank_based_score(rank, total=100):
|
| 173 |
+
ratio = (rank - 1) / (total - 1)
|
| 174 |
+
decay = ratio ** 0.55
|
| 175 |
+
score = 1.0 - 0.65 * decay
|
| 176 |
+
return round(score, 6)
|
pipeline/text_builder.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .config import MAX_TEXT_BM25, MAX_TEXT_RERANK
|
| 2 |
+
|
| 3 |
+
def join_parts(parts, limit=None):
|
| 4 |
+
filtered = []
|
| 5 |
+
for part in parts:
|
| 6 |
+
if part:
|
| 7 |
+
filtered.append(part)
|
| 8 |
+
text = " ".join(filtered)
|
| 9 |
+
if limit:
|
| 10 |
+
return text[:limit]
|
| 11 |
+
return text
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_skill_names(candidate):
|
| 15 |
+
names = []
|
| 16 |
+
for skill in candidate.get("skills", []):
|
| 17 |
+
name = skill.get("name", "")
|
| 18 |
+
if name:
|
| 19 |
+
names.append(name)
|
| 20 |
+
return " ".join(names)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def build_text_short(candidate):
|
| 24 |
+
profile = candidate.get("profile", {})
|
| 25 |
+
|
| 26 |
+
parts = [
|
| 27 |
+
profile.get("headline", ""),
|
| 28 |
+
profile.get("summary", "")[:200],
|
| 29 |
+
profile.get("current_title", ""),
|
| 30 |
+
profile.get("current_industry", ""),
|
| 31 |
+
get_skill_names(candidate),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
for job in candidate.get("career_history", [])[:2]:
|
| 35 |
+
title = job.get("title", "")
|
| 36 |
+
description = job.get("description", "")[:80]
|
| 37 |
+
parts.append(f"{title} {description}")
|
| 38 |
+
|
| 39 |
+
return join_parts(parts, limit=MAX_TEXT_BM25)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_text_full(candidate):
|
| 43 |
+
profile = candidate.get("profile", {})
|
| 44 |
+
|
| 45 |
+
skill_list = []
|
| 46 |
+
for skill in candidate.get("skills", []):
|
| 47 |
+
name = skill.get("name", "")
|
| 48 |
+
if name:
|
| 49 |
+
skill_list.append(name)
|
| 50 |
+
|
| 51 |
+
parts = [
|
| 52 |
+
profile.get("headline", ""),
|
| 53 |
+
profile.get("summary", ""),
|
| 54 |
+
f"{profile.get('current_title', '')} at {profile.get('current_company', '')}",
|
| 55 |
+
f"{profile.get('years_of_experience', 0)} years experience",
|
| 56 |
+
f"Skills: {', '.join(skill_list)}",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
for job in candidate.get("career_history", [])[:3]:
|
| 60 |
+
title = job.get("title", "")
|
| 61 |
+
company = job.get("company", "")
|
| 62 |
+
description = job.get("description", "")[:150]
|
| 63 |
+
parts.append(f"{title} at {company}: {description}")
|
| 64 |
+
|
| 65 |
+
for edu in candidate.get("education", [])[:2]:
|
| 66 |
+
degree = edu.get("degree", "")
|
| 67 |
+
field = edu.get("field_of_study", "")
|
| 68 |
+
institution = edu.get("institution", "")
|
| 69 |
+
parts.append(f"{degree} {field} {institution}")
|
| 70 |
+
|
| 71 |
+
return join_parts(parts, limit=MAX_TEXT_RERANK)
|
rank.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse, csv, gc, json, os, resource, sys, time
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import bm25s
|
| 4 |
+
import Stemmer
|
| 5 |
+
import numpy as np
|
| 6 |
+
from flashrank import Ranker, RerankRequest
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from pipeline.config import (
|
| 9 |
+
JD_BM25, JD_SEMANTIC, BM25_TOP_K, FINAL_TOP_K,
|
| 10 |
+
FLASHRANK_BATCH_SIZE, PROJECT_DIR,
|
| 11 |
+
)
|
| 12 |
+
from pipeline.filters import is_honeypot, passes_prefilter
|
| 13 |
+
from pipeline.text_builder import build_text_short, build_text_full
|
| 14 |
+
from pipeline.scoring import behavioral_multiplier, rank_based_score
|
| 15 |
+
from pipeline.reasoning import generate_reasoning
|
| 16 |
+
|
| 17 |
+
# Memory + thread limits
|
| 18 |
+
MAX_RAM = 16 * 1024 * 1024 * 1024 # 16 GiB
|
| 19 |
+
try:
|
| 20 |
+
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
|
| 21 |
+
resource.setrlimit(resource.RLIMIT_AS, (MAX_RAM, hard))
|
| 22 |
+
except (ValueError, resource.error):
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
# Auto assign threads based on available RAM
|
| 26 |
+
try:
|
| 27 |
+
total_ram_gb = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / (1024 ** 3)
|
| 28 |
+
if total_ram_gb > 8:
|
| 29 |
+
num_threads = "3"
|
| 30 |
+
else:
|
| 31 |
+
num_threads = "2"
|
| 32 |
+
except Exception:
|
| 33 |
+
num_threads = "2"
|
| 34 |
+
|
| 35 |
+
os.environ.setdefault("OMP_NUM_THREADS", num_threads)
|
| 36 |
+
os.environ.setdefault("OPENBLAS_NUM_THREADS", num_threads)
|
| 37 |
+
os.environ.setdefault("MKL_NUM_THREADS", num_threads)
|
| 38 |
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 39 |
+
print(f"System RAM: {total_ram_gb:.1f}GB | Using {num_threads} threads")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def mem_mb():
|
| 43 |
+
# Current process RSS in MB (Linux).
|
| 44 |
+
try:
|
| 45 |
+
with open("/proc/self/status") as f:
|
| 46 |
+
for line in f:
|
| 47 |
+
if line.startswith("VmRSS:"):
|
| 48 |
+
return int(line.split()[1]) / 1024
|
| 49 |
+
except Exception:
|
| 50 |
+
pass
|
| 51 |
+
return 0.0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main():
|
| 55 |
+
t0 = time.time()
|
| 56 |
+
ap = argparse.ArgumentParser(description="Redrob candidate ranking pipeline")
|
| 57 |
+
ap.add_argument("--candidates", required=True, help="Path to candidates.jsonl")
|
| 58 |
+
ap.add_argument("--out", required=True, help="Output CSV path")
|
| 59 |
+
args = ap.parse_args()
|
| 60 |
+
cpath, opath = Path(args.candidates), Path(args.out)
|
| 61 |
+
|
| 62 |
+
# Stage 1: Stream + filter
|
| 63 |
+
print("[1/5] Streaming + filtering …")
|
| 64 |
+
texts, cand_ids, offsets = [], [], []
|
| 65 |
+
total = hp = filt = 0
|
| 66 |
+
|
| 67 |
+
with open(cpath, "rb") as fh:
|
| 68 |
+
while True:
|
| 69 |
+
off = fh.tell()
|
| 70 |
+
line = fh.readline()
|
| 71 |
+
if not line:
|
| 72 |
+
break
|
| 73 |
+
total += 1
|
| 74 |
+
c = json.loads(line)
|
| 75 |
+
if is_honeypot(c):
|
| 76 |
+
hp += 1; del c; continue
|
| 77 |
+
if not passes_prefilter(c):
|
| 78 |
+
filt += 1; del c; continue
|
| 79 |
+
texts.append(build_text_short(c))
|
| 80 |
+
cand_ids.append(c["candidate_id"])
|
| 81 |
+
offsets.append(off)
|
| 82 |
+
del c
|
| 83 |
+
|
| 84 |
+
kept = len(texts)
|
| 85 |
+
print(f" Total={total} Honeypots={hp} Filtered={filt} Kept={kept}")
|
| 86 |
+
print(f" Stage 1: {time.time()-t0:.1f}s RSS={mem_mb():.0f}MB")
|
| 87 |
+
gc.collect()
|
| 88 |
+
|
| 89 |
+
# Stage 2: Hybrid Retrieval (BM25 + Dense Vectors)
|
| 90 |
+
t1 = time.time()
|
| 91 |
+
print("[2/5] Hybrid indexing + retrieval (BM25 + Embeddings) …")
|
| 92 |
+
|
| 93 |
+
# 2a. BM25
|
| 94 |
+
stemmer = Stemmer.Stemmer("english")
|
| 95 |
+
corpus_tok = bm25s.tokenize(texts, stemmer=stemmer, stopwords="en")
|
| 96 |
+
retriever = bm25s.BM25()
|
| 97 |
+
retriever.index(corpus_tok)
|
| 98 |
+
|
| 99 |
+
q_tok = bm25s.tokenize([JD_BM25], stemmer=stemmer, stopwords="en")
|
| 100 |
+
k = min(BM25_TOP_K, kept)
|
| 101 |
+
|
| 102 |
+
# Retrieve all valid candidates to combine scores
|
| 103 |
+
res, bm25_scores_full = retriever.retrieve(q_tok, k=kept)
|
| 104 |
+
bm25_sorted_idxs = res[0]
|
| 105 |
+
bm25_sorted_scores = bm25_scores_full[0]
|
| 106 |
+
|
| 107 |
+
bm25_original_order = np.zeros(kept, dtype=np.float32)
|
| 108 |
+
bm25_original_order[bm25_sorted_idxs] = bm25_sorted_scores
|
| 109 |
+
|
| 110 |
+
del retriever, corpus_tok, q_tok, texts, stemmer, res, bm25_scores_full
|
| 111 |
+
gc.collect()
|
| 112 |
+
|
| 113 |
+
# 2b. Dense Embeddings
|
| 114 |
+
print(" Loading embeddings...")
|
| 115 |
+
all_dense_embs = np.load("data/candidate_embeddings.npy")
|
| 116 |
+
with open("data/candidate_ids.json", "r") as f:
|
| 117 |
+
all_dense_ids = json.load(f)
|
| 118 |
+
|
| 119 |
+
dense_id_to_idx = {cid: i for i, cid in enumerate(all_dense_ids)}
|
| 120 |
+
|
| 121 |
+
valid_dense_embs = np.zeros((kept, all_dense_embs.shape[1]), dtype=np.float32)
|
| 122 |
+
for i, cid in enumerate(cand_ids):
|
| 123 |
+
valid_dense_embs[i] = all_dense_embs[dense_id_to_idx[cid]]
|
| 124 |
+
|
| 125 |
+
del all_dense_embs, all_dense_ids, dense_id_to_idx
|
| 126 |
+
gc.collect()
|
| 127 |
+
|
| 128 |
+
print(" Embedding JD and computing cosine similarities...")
|
| 129 |
+
model = SentenceTransformer(str(PROJECT_DIR / "weights" / "bge-small-en-v1.5"), device="cpu")
|
| 130 |
+
jd_emb = model.encode([JD_SEMANTIC], normalize_embeddings=True)[0]
|
| 131 |
+
dense_scores = valid_dense_embs @ jd_emb
|
| 132 |
+
|
| 133 |
+
del model, valid_dense_embs
|
| 134 |
+
gc.collect()
|
| 135 |
+
|
| 136 |
+
# 2c. Score Normalization & Fusion
|
| 137 |
+
def normalize(arr):
|
| 138 |
+
min_v, max_v = arr.min(), arr.max()
|
| 139 |
+
if max_v > min_v:
|
| 140 |
+
return (arr - min_v) / (max_v - min_v)
|
| 141 |
+
return arr
|
| 142 |
+
|
| 143 |
+
dense_norm = normalize(dense_scores)
|
| 144 |
+
bm25_norm = normalize(bm25_original_order)
|
| 145 |
+
|
| 146 |
+
# 70% Dense Semantic, 30% Exact BM25 Keyword match
|
| 147 |
+
hybrid_scores = 0.7 * dense_norm + 0.3 * bm25_norm
|
| 148 |
+
|
| 149 |
+
top_indices = np.argsort(hybrid_scores)[::-1][:k]
|
| 150 |
+
bm25_idxs = top_indices.tolist()
|
| 151 |
+
|
| 152 |
+
print(f" Shortlisted {len(bm25_idxs)} candidates via Hybrid Search")
|
| 153 |
+
print(f" Stage 2: {time.time()-t1:.1f}s RSS={mem_mb():.0f}MB")
|
| 154 |
+
|
| 155 |
+
# Stage 3: Re-read shortlisted candidates
|
| 156 |
+
t2 = time.time()
|
| 157 |
+
print("[3/5] Re-reading shortlisted candidates …")
|
| 158 |
+
need = sorted({offsets[i] for i in bm25_idxs})
|
| 159 |
+
off2cand = {}
|
| 160 |
+
with open(cpath, "rb") as fh:
|
| 161 |
+
for off in need:
|
| 162 |
+
fh.seek(off)
|
| 163 |
+
off2cand[off] = json.loads(fh.readline())
|
| 164 |
+
|
| 165 |
+
rerank_cands, rerank_texts = [], []
|
| 166 |
+
for i in bm25_idxs:
|
| 167 |
+
c = off2cand[offsets[i]]
|
| 168 |
+
rerank_cands.append(c)
|
| 169 |
+
rerank_texts.append(build_text_full(c))
|
| 170 |
+
|
| 171 |
+
del off2cand, need, bm25_idxs, offsets, cand_ids
|
| 172 |
+
gc.collect()
|
| 173 |
+
print(f" Loaded {len(rerank_cands)} candidates")
|
| 174 |
+
print(f" Stage 3: {time.time()-t2:.1f}s RSS={mem_mb():.0f}MB")
|
| 175 |
+
|
| 176 |
+
# Stage 4: FlashRank batch reranking
|
| 177 |
+
t3 = time.time()
|
| 178 |
+
BS = FLASHRANK_BATCH_SIZE
|
| 179 |
+
n = len(rerank_texts)
|
| 180 |
+
n_batches = (n + BS - 1) // BS
|
| 181 |
+
print(f"[4/5] FlashRank reranking ({BS}/batch, {n_batches} batches) …")
|
| 182 |
+
|
| 183 |
+
ranker = Ranker(
|
| 184 |
+
model_name="ms-marco-MiniLM-L-12-v2",
|
| 185 |
+
cache_dir=str(PROJECT_DIR / "weights"),
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
all_results = []
|
| 189 |
+
for b in range(n_batches):
|
| 190 |
+
start, end = b * BS, min((b + 1) * BS, n)
|
| 191 |
+
passages = [{"id": start + j, "text": rerank_texts[start + j]}
|
| 192 |
+
for j in range(end - start)]
|
| 193 |
+
rr = ranker.rerank(RerankRequest(query=JD_SEMANTIC, passages=passages))
|
| 194 |
+
all_results.extend(rr)
|
| 195 |
+
del passages, rr; gc.collect()
|
| 196 |
+
print(f" Batch {b+1}/{n_batches} done RSS={mem_mb():.0f}MB")
|
| 197 |
+
|
| 198 |
+
del ranker, rerank_texts
|
| 199 |
+
gc.collect()
|
| 200 |
+
print(f" Reranked {len(all_results)} passages")
|
| 201 |
+
print(f" Stage 4: {time.time()-t3:.1f}s RSS={mem_mb():.0f}MB")
|
| 202 |
+
|
| 203 |
+
# Stage 5: Score + output
|
| 204 |
+
t4 = time.time()
|
| 205 |
+
print("[5/5] Scoring + output …")
|
| 206 |
+
|
| 207 |
+
scored = []
|
| 208 |
+
for item in all_results:
|
| 209 |
+
pid = item.get("id")
|
| 210 |
+
if pid is None or int(pid) >= len(rerank_cands):
|
| 211 |
+
continue
|
| 212 |
+
c = rerank_cands[int(pid)]
|
| 213 |
+
final = float(item.get("score", 0)) * behavioral_multiplier(c)
|
| 214 |
+
scored.append((final, c["candidate_id"], c))
|
| 215 |
+
|
| 216 |
+
del all_results; gc.collect()
|
| 217 |
+
|
| 218 |
+
# Deterministic sort: score DESC, candidate_id ASC
|
| 219 |
+
scored.sort(key=lambda x: (-x[0], x[1]))
|
| 220 |
+
top = scored[:FINAL_TOP_K]
|
| 221 |
+
|
| 222 |
+
rows = []
|
| 223 |
+
with open(opath, "w", newline="", encoding="utf-8") as fh:
|
| 224 |
+
w = csv.DictWriter(fh, fieldnames=["candidate_id", "rank", "score", "reasoning"])
|
| 225 |
+
w.writeheader()
|
| 226 |
+
|
| 227 |
+
# Write each row to disk as reasoning is generated
|
| 228 |
+
for rank, (_, cid, c) in enumerate(top, 1):
|
| 229 |
+
row = {
|
| 230 |
+
"candidate_id": cid,
|
| 231 |
+
"rank": rank,
|
| 232 |
+
"score": f"{rank_based_score(rank):.6f}",
|
| 233 |
+
"reasoning": generate_reasoning(c, rank),
|
| 234 |
+
}
|
| 235 |
+
w.writerow(row)
|
| 236 |
+
fh.flush()
|
| 237 |
+
rows.append(row)
|
| 238 |
+
print(f"\r -> Generated reasoning for rank {rank}/{len(top)}", end="", flush=True)
|
| 239 |
+
|
| 240 |
+
elapsed = time.time() - t0
|
| 241 |
+
print(f"\n Streamed and wrote {len(rows)} rows to {opath} in {elapsed:.1f}s")
|
| 242 |
+
|
| 243 |
+
# Sanity checks
|
| 244 |
+
assert len(rows) <= FINAL_TOP_K
|
| 245 |
+
sc = [float(r["score"]) for r in rows]
|
| 246 |
+
for i in range(1, len(sc)):
|
| 247 |
+
assert sc[i] <= sc[i - 1], f"Non-monotonic at rank {i + 1}"
|
| 248 |
+
print(" All checks passed.")
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
bm25s
|
| 2 |
+
PyStemmer
|
| 3 |
+
flashrank
|
| 4 |
+
onnxruntime
|
| 5 |
+
pandas
|
| 6 |
+
numpy
|
| 7 |
+
scipy
|
| 8 |
+
streamlit
|
| 9 |
+
# NOTE: The CPU version of PyTorch is used here to meet hackathon storage limits.
|
| 10 |
+
# If you want to use a GPU (e.g. for computing precomputed_features.npy faster),
|
| 11 |
+
# remove or comment out the cpu extra-index-url line below:
|
| 12 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 13 |
+
torch
|
| 14 |
+
sentence-transformers
|
| 15 |
+
llama-cpp-python
|
validate_submission.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Validate submission CSV per challenge rules (sections 2–3).
|
| 4 |
+
Row 1 = header. Rows 2–101 = exactly 100 data rows. CSV only.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import csv
|
| 8 |
+
import re
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
REQUIRED_HEADER = ["candidate_id", "rank", "score", "reasoning"]
|
| 13 |
+
CANDIDATE_ID_PATTERN = re.compile(r"^CAND_[0-9]{7}$")
|
| 14 |
+
DATA_ROW_START = 2
|
| 15 |
+
EXPECTED_DATA_ROWS = 100
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def validate_submission(csv_path):
|
| 19 |
+
errors = []
|
| 20 |
+
path = Path(csv_path)
|
| 21 |
+
|
| 22 |
+
if path.suffix.lower() != ".csv":
|
| 23 |
+
errors.append("Filename must use a .csv extension.")
|
| 24 |
+
elif not path.stem:
|
| 25 |
+
errors.append("Filename must be your registered participant ID (e.g. team_xxx.csv).")
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
with open(path, "r", encoding="utf-8", newline="") as f:
|
| 29 |
+
reader = csv.reader(f)
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
header = next(reader)
|
| 33 |
+
except StopIteration:
|
| 34 |
+
errors.append("Row 1 must be the header row; file is empty.")
|
| 35 |
+
return errors
|
| 36 |
+
|
| 37 |
+
# Row 1: column names and their order come from this line only
|
| 38 |
+
if header != REQUIRED_HEADER:
|
| 39 |
+
errors.append(
|
| 40 |
+
"Row 1 (header) must be exactly:\n"
|
| 41 |
+
f" {','.join(REQUIRED_HEADER)}\n"
|
| 42 |
+
f"Found:\n"
|
| 43 |
+
f" {','.join(header)}"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
data_rows = []
|
| 47 |
+
for row in reader:
|
| 48 |
+
if any(cell.strip() for cell in row):
|
| 49 |
+
data_rows.append(row)
|
| 50 |
+
|
| 51 |
+
except UnicodeDecodeError:
|
| 52 |
+
errors.append("File must be UTF-8 encoded.")
|
| 53 |
+
return errors
|
| 54 |
+
except OSError as e:
|
| 55 |
+
errors.append(f"Cannot read file: {e}")
|
| 56 |
+
return errors
|
| 57 |
+
|
| 58 |
+
n = len(data_rows)
|
| 59 |
+
if n != EXPECTED_DATA_ROWS:
|
| 60 |
+
errors.append(
|
| 61 |
+
f"After the header (row 1), there must be exactly {EXPECTED_DATA_ROWS} "
|
| 62 |
+
f"data rows (rows {DATA_ROW_START}–{DATA_ROW_START + EXPECTED_DATA_ROWS - 1}); "
|
| 63 |
+
f"found {n}."
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
seen_ids = set()
|
| 67 |
+
seen_ranks = set()
|
| 68 |
+
by_rank = []
|
| 69 |
+
|
| 70 |
+
for i, cells in enumerate(data_rows):
|
| 71 |
+
row_num = DATA_ROW_START + i
|
| 72 |
+
|
| 73 |
+
if len(cells) != len(REQUIRED_HEADER):
|
| 74 |
+
errors.append(
|
| 75 |
+
f"Row {row_num}: expected {len(REQUIRED_HEADER)} columns "
|
| 76 |
+
f"({','.join(REQUIRED_HEADER)}), got {len(cells)}."
|
| 77 |
+
)
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
row = dict(zip(REQUIRED_HEADER, cells))
|
| 81 |
+
cid = row["candidate_id"].strip()
|
| 82 |
+
rank_s = row["rank"].strip()
|
| 83 |
+
score_s = row["score"].strip()
|
| 84 |
+
|
| 85 |
+
if not cid:
|
| 86 |
+
errors.append(f"Row {row_num}: candidate_id is required.")
|
| 87 |
+
elif not CANDIDATE_ID_PATTERN.match(cid):
|
| 88 |
+
errors.append(
|
| 89 |
+
f"Row {row_num}: candidate_id must be CAND_XXXXXXX (7 digits)."
|
| 90 |
+
)
|
| 91 |
+
elif cid in seen_ids:
|
| 92 |
+
errors.append(f"Row {row_num}: duplicate candidate_id '{cid}'.")
|
| 93 |
+
else:
|
| 94 |
+
seen_ids.add(cid)
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
rank = int(rank_s)
|
| 98 |
+
if str(rank) != rank_s:
|
| 99 |
+
raise ValueError
|
| 100 |
+
if not 1 <= rank <= 100:
|
| 101 |
+
errors.append(f"Row {row_num}: rank must be between 1 and 100.")
|
| 102 |
+
elif rank in seen_ranks:
|
| 103 |
+
errors.append(f"Row {row_num}: duplicate rank {rank}.")
|
| 104 |
+
else:
|
| 105 |
+
seen_ranks.add(rank)
|
| 106 |
+
except ValueError:
|
| 107 |
+
errors.append(f"Row {row_num}: rank must be an integer (1–100).")
|
| 108 |
+
rank = None
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
score = float(score_s)
|
| 112 |
+
except ValueError:
|
| 113 |
+
errors.append(f"Row {row_num}: score must be a float.")
|
| 114 |
+
score = None
|
| 115 |
+
|
| 116 |
+
if rank is not None and score is not None and cid:
|
| 117 |
+
by_rank.append((rank, score, cid))
|
| 118 |
+
|
| 119 |
+
missing = set(range(1, 101)) - seen_ranks
|
| 120 |
+
if missing:
|
| 121 |
+
errors.append(
|
| 122 |
+
f"Each rank 1–100 must appear exactly once; missing: {sorted(missing)}"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
by_rank.sort(key=lambda x: x[0])
|
| 126 |
+
|
| 127 |
+
for i in range(len(by_rank) - 1):
|
| 128 |
+
r1, s1, _ = by_rank[i]
|
| 129 |
+
r2, s2, _ = by_rank[i + 1]
|
| 130 |
+
if s1 < s2:
|
| 131 |
+
errors.append(
|
| 132 |
+
f"score must be non-increasing by rank: "
|
| 133 |
+
f"rank {r1} ({s1}) < rank {r2} ({s2})."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
for i in range(len(by_rank) - 1):
|
| 137 |
+
r1, s1, c1 = by_rank[i]
|
| 138 |
+
r2, s2, c2 = by_rank[i + 1]
|
| 139 |
+
if s1 == s2 and c1 > c2:
|
| 140 |
+
errors.append(
|
| 141 |
+
f"Equal scores at ranks {r1} and {r2}: "
|
| 142 |
+
f"tie-break requires candidate_id ascending "
|
| 143 |
+
f"({c1!r} > {c2!r})."
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
return errors
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def main():
|
| 150 |
+
if len(sys.argv) != 2:
|
| 151 |
+
print("Usage: python validate_submission.py <participant_id>.csv")
|
| 152 |
+
sys.exit(1)
|
| 153 |
+
|
| 154 |
+
errors = validate_submission(sys.argv[1])
|
| 155 |
+
if errors:
|
| 156 |
+
print(f"Validation failed ({len(errors)} issue(s)):\n")
|
| 157 |
+
for e in errors:
|
| 158 |
+
print(f"- {e}")
|
| 159 |
+
sys.exit(1)
|
| 160 |
+
|
| 161 |
+
print("Submission is valid.")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
main()
|