AnshulS commited on
Commit
04fa7f5
·
verified ·
1 Parent(s): cbb8b01

Update retriever.py

Browse files
Files changed (1) hide show
  1. retriever.py +103 -31
retriever.py CHANGED
@@ -1,38 +1,110 @@
1
  import pandas as pd
2
- from sentence_transformers import SentenceTransformer, util
 
 
3
 
4
- model = SentenceTransformer("all-MiniLM-L6-v2")
5
-
6
- def get_relevant_passages(query, df, top_k=20):
7
- # Create a copy to avoid modifying the original dataframe
8
- df_copy = df.copy()
 
 
 
 
 
 
 
9
 
10
- # Ensure URL field is properly formatted
11
- if 'url' in df_copy.columns:
12
- # Clean up URLs if needed
13
- df_copy['url'] = df_copy['url'].astype(str)
14
- # Ensure URLs start with http or https
15
- mask = ~df_copy['url'].str.startswith(('http://', 'https://'))
16
- df_copy.loc[mask, 'url'] = 'https://www.shl.com/' + df_copy.loc[mask, 'url'].str.lstrip('/')
17
 
18
- # Format test_type for better representation
19
- def format_test_type(test_types):
20
- if isinstance(test_types, list):
21
- return ', '.join(test_types)
22
- return str(test_types)
23
 
24
- # Concatenate all fields into a single string per row
25
- corpus = df_copy.apply(
26
- lambda row: f"{row['description']} "
27
- f"Test types: {format_test_type(row['test_type'])}. "
28
- f"Adaptive support: {row['adaptive_support']}. "
29
- f"Remote support: {row['remote_support']}. "
30
- f"Duration: {row['duration'] if pd.notna(row['duration']) else 'N/A'} minutes.",
31
- axis=1
32
- ).tolist()
33
 
34
- corpus_embeddings = model.encode(corpus, convert_to_tensor=True)
35
- query_embedding = model.encode(query, convert_to_tensor=True)
36
- hits = util.semantic_search(query_embedding, corpus_embeddings, top_k=top_k)[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- return df_copy.iloc[[hit['corpus_id'] for hit in hits]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Ensure clean URLs
11
+ # Check if the second column contains URLs or just IDs
12
+ second_col = df.iloc[:, 1].astype(str)
13
+ if second_col.str.contains('http').any() or second_col.str.contains('www').any():
14
+ df["url"] = second_col # Already has full URLs
15
+ else:
16
+ # Create full URLs from IDs
17
+ df["url"] = "https://www.shl.com/" + second_col.str.replace(r'^[\s/]*', '', regex=True)
18
 
19
+ df["remote_support"] = df.iloc[:, 2].map(lambda x: "Yes" if x == "T" else "No")
20
+ df["adaptive_support"] = df.iloc[:, 3].map(lambda x: "Yes" if x == "T" else "No")
 
 
 
 
 
21
 
22
+ # Handle test_type with error checking
23
+ df["test_type"] = df.iloc[:, 4].astype(str).str.split("\\n")
 
 
 
24
 
25
+ df["description"] = df.iloc[:, 5]
 
 
 
 
 
 
 
 
26
 
27
+ # Extract duration with error handling
28
+ df["duration"] = pd.to_numeric(
29
+ df.iloc[:, 8].astype(str).str.extract(r'(\d+)')[0],
30
+ errors='coerce'
31
+ )
32
+
33
+ return df[["url", "adaptive_support", "remote_support", "description", "duration", "test_type"]]
34
+
35
+ try:
36
+ df = pd.read_csv("assesments.csv")
37
+ df_clean = clean_df(df)
38
+ except Exception as e:
39
+ print(f"Error loading or cleaning data: {e}")
40
+ # Create an empty DataFrame with required columns as fallback
41
+ df_clean = pd.DataFrame(columns=["url", "adaptive_support", "remote_support",
42
+ "description", "duration", "test_type"])
43
+
44
+ def validate_and_fix_urls(candidates):
45
+ """Validates and fixes URLs in candidate assessments."""
46
+ for candidate in candidates:
47
+ # Ensure URL exists
48
+ if 'url' not in candidate or not candidate['url']:
49
+ candidate['url'] = 'https://www.shl.com/missing-url'
50
+ continue
51
+
52
+ url = str(candidate['url'])
53
+
54
+ # Fix URLs that are just numbers
55
+ if url.isdigit() or (url.startswith('https://www.shl.com') and url[len('https://www.shl.com'):].isdigit()):
56
+ candidate['url'] = f"https://www.shl.com/{url.replace('https://www.shl.com', '')}"
57
+ continue
58
+
59
+ # Add protocol if missing
60
+ if not url.startswith(('http://', 'https://')):
61
+ candidate['url'] = f"https://{url}"
62
+
63
+ return candidates
64
+
65
+ def recommend(query):
66
+ if not query.strip():
67
+ return {"error": "Please enter a job description"}
68
 
69
+ try:
70
+ # Print some debug info
71
+ print(f"Processing query: {query[:50]}...")
72
+
73
+ top_k_df = get_relevant_passages(query, df_clean, top_k=20)
74
+
75
+ # Debug: Check URLs in retrieved data
76
+ print(f"Retrieved {len(top_k_df)} assessments")
77
+ if not top_k_df.empty:
78
+ print(f"Sample URLs from retrieval: {top_k_df['url'].iloc[:3].tolist()}")
79
+
80
+ candidates = top_k_df.to_dict(orient="records")
81
+
82
+ # Additional URL validation before sending to reranker
83
+ for c in candidates:
84
+ if 'url' in c:
85
+ if not str(c['url']).startswith(('http://', 'https://')):
86
+ c['url'] = f"https://www.shl.com/{str(c['url']).lstrip('/')}"
87
+
88
+ result = rerank(query, candidates)
89
+
90
+ # Post-process result to ensure URLs are properly formatted
91
+ if 'recommended_assessments' in result:
92
+ result['recommended_assessments'] = validate_and_fix_urls(result['recommended_assessments'])
93
+
94
+ return result
95
+ except Exception as e:
96
+ import traceback
97
+ error_details = traceback.format_exc()
98
+ print(f"Error: {str(e)}\n{error_details}")
99
+ return {"error": f"Error processing request: {str(e)}"}
100
+
101
+ iface = gr.Interface(
102
+ fn=recommend,
103
+ inputs=gr.Textbox(label="Enter Job Description", lines=4),
104
+ outputs="json",
105
+ title="SHL Assessment Recommender",
106
+ description="Paste a job description to get the most relevant SHL assessments."
107
+ )
108
+
109
+ if __name__ == "__main__":
110
+ iface.launch()