Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import gradio as gr
|
3 |
+
from retriever import get_relevant_passages
|
4 |
+
from reranker import rerank
|
5 |
+
|
6 |
+
# Load and clean CSV
|
7 |
+
def clean_df(df):
|
8 |
+
df = df.copy()
|
9 |
+
|
10 |
+
# Get column names for reference
|
11 |
+
print(f"Original columns: {df.columns}")
|
12 |
+
|
13 |
+
# Ensure clean URLs from the second column
|
14 |
+
second_col = df.iloc[:, 3].astype(str) # Pre-packaged Job Solutions column
|
15 |
+
|
16 |
+
if second_col.str.contains('http').any() or second_col.str.contains('www').any():
|
17 |
+
df["url"] = second_col # Already has full URLs
|
18 |
+
else:
|
19 |
+
# Create full URLs from IDs
|
20 |
+
df["url"] = "https://www.shl.com" + second_col.str.replace(r'^(?!/)', '/', regex=True)
|
21 |
+
|
22 |
+
# Map T/F to Yes/No for remote testing and adaptive support
|
23 |
+
df["remote_support"] = df.iloc[:, 4].map(lambda x: "Yes" if x == "T" else "No")
|
24 |
+
df["adaptive_support"] = df.iloc[:, 5].map(lambda x: "Yes" if x == "T" else "No")
|
25 |
+
|
26 |
+
# Handle test_type properly - convert string representation of list to actual list
|
27 |
+
df["test_type"] = df.iloc[:, 6].apply(lambda x: eval(x) if isinstance(x, str) else x)
|
28 |
+
|
29 |
+
# Get description from column 7
|
30 |
+
df["description"] = df.iloc[:, 7]
|
31 |
+
|
32 |
+
# Extract duration with error handling from column 10
|
33 |
+
df["duration"] = pd.to_numeric(
|
34 |
+
df.iloc[:, 10].astype(str).str.extract(r'(\d+)')[0],
|
35 |
+
errors='coerce'
|
36 |
+
)
|
37 |
+
|
38 |
+
# Print sample of cleaned data for debugging
|
39 |
+
print(f"Sample of cleaned data: {df[['url', 'adaptive_support', 'remote_support', 'description', 'duration', 'test_type']].head(2)}")
|
40 |
+
|
41 |
+
return df[["url", "adaptive_support", "remote_support", "description", "duration", "test_type"]]
|
42 |
+
|
43 |
+
try:
|
44 |
+
# Load CSV with explicit encoding
|
45 |
+
df = pd.read_csv("assesments.csv", encoding='utf-8')
|
46 |
+
print(f"CSV loaded successfully with {len(df)} rows")
|
47 |
+
df_clean = clean_df(df)
|
48 |
+
except Exception as e:
|
49 |
+
print(f"Error loading or cleaning data: {e}")
|
50 |
+
# Create an empty DataFrame with required columns as fallback
|
51 |
+
df_clean = pd.DataFrame(columns=["url", "adaptive_support", "remote_support",
|
52 |
+
"description", "duration", "test_type"])
|
53 |
+
|
54 |
+
def validate_and_fix_urls(candidates):
|
55 |
+
"""Validates and fixes URLs in candidate assessments."""
|
56 |
+
for candidate in candidates:
|
57 |
+
# Skip if candidate is not a dictionary
|
58 |
+
if not isinstance(candidate, dict):
|
59 |
+
continue
|
60 |
+
|
61 |
+
# Ensure URL exists
|
62 |
+
if 'url' not in candidate or not candidate['url']:
|
63 |
+
candidate['url'] = 'https://www.shl.com/missing-url'
|
64 |
+
continue
|
65 |
+
|
66 |
+
url = str(candidate['url'])
|
67 |
+
|
68 |
+
# Fix URLs that are just numbers
|
69 |
+
if url.isdigit():
|
70 |
+
candidate['url'] = f"https://www.shl.com/{url}"
|
71 |
+
continue
|
72 |
+
|
73 |
+
# Add protocol if missing
|
74 |
+
if not url.startswith(('http://', 'https://')):
|
75 |
+
candidate['url'] = f"https://www.shl.com{url}" if url.startswith('/') else f"https://www.shl.com/{url}"
|
76 |
+
|
77 |
+
return candidates
|
78 |
+
|
79 |
+
def recommend(query):
|
80 |
+
if not query.strip():
|
81 |
+
return {"error": "Please enter a job description"}
|
82 |
+
|
83 |
+
try:
|
84 |
+
# Print some debug info
|
85 |
+
print(f"Processing query: {query[:50]}...")
|
86 |
+
|
87 |
+
# Get relevant passages
|
88 |
+
top_k_df = get_relevant_passages(query, df_clean, top_k=20)
|
89 |
+
|
90 |
+
# Debug: Check if we got any results
|
91 |
+
print(f"Retrieved {len(top_k_df)} assessments")
|
92 |
+
|
93 |
+
if top_k_df.empty:
|
94 |
+
return {"error": "No matching assessments found"}
|
95 |
+
|
96 |
+
# Convert test_type to list if it's not already
|
97 |
+
top_k_df['test_type'] = top_k_df['test_type'].apply(
|
98 |
+
lambda x: x if isinstance(x, list) else
|
99 |
+
(eval(x) if isinstance(x, str) and x.startswith('[') else [str(x)])
|
100 |
+
)
|
101 |
+
|
102 |
+
# Handle nan values for duration
|
103 |
+
top_k_df['duration'] = top_k_df['duration'].fillna(-1).astype(int)
|
104 |
+
top_k_df.loc[top_k_df['duration'] == -1, 'duration'] = None
|
105 |
+
|
106 |
+
# Convert DataFrame to list of dictionaries
|
107 |
+
candidates = top_k_df.to_dict(orient="records")
|
108 |
+
|
109 |
+
# Additional URL validation
|
110 |
+
candidates = validate_and_fix_urls(candidates)
|
111 |
+
|
112 |
+
# Print sample of data being sent to reranker
|
113 |
+
if candidates:
|
114 |
+
print(f"Sample candidate being sent to reranker: {candidates[0]}")
|
115 |
+
|
116 |
+
# Get recommendations
|
117 |
+
result = rerank(query, candidates)
|
118 |
+
|
119 |
+
# Post-process result
|
120 |
+
if 'recommended_assessments' in result:
|
121 |
+
result['recommended_assessments'] = validate_and_fix_urls(result['recommended_assessments'])
|
122 |
+
print(f"Returning {len(result['recommended_assessments'])} recommended assessments")
|
123 |
+
|
124 |
+
return result
|
125 |
+
except Exception as e:
|
126 |
+
import traceback
|
127 |
+
error_details = traceback.format_exc()
|
128 |
+
print(f"Error: {str(e)}\n{error_details}")
|
129 |
+
return {"error": f"Error processing request: {str(e)}"}
|
130 |
+
|
131 |
+
iface = gr.Interface(
|
132 |
+
fn=recommend,
|
133 |
+
inputs=gr.Textbox(label="Enter Job Description", lines=4),
|
134 |
+
outputs="json",
|
135 |
+
title="SHL Assessment Recommender",
|
136 |
+
description="Paste a job description to get the most relevant SHL assessments."
|
137 |
+
)
|
138 |
+
|
139 |
+
if __name__ == "__main__":
|
140 |
+
iface.launch()
|