AnshulS commited on
Commit
bb65b65
·
verified ·
1 Parent(s): ba3e546

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -24
app.py CHANGED
@@ -1,25 +1,21 @@
1
  import pandas as pd
2
  import gradio as gr
3
  import json
4
- from fastapi import FastAPI, Request
5
  from fastapi.responses import JSONResponse
6
-
7
  from retriever import get_relevant_passages
8
  from reranker import rerank
9
 
10
- # Top-level FastAPI app declaration
11
- app = FastAPI()
12
-
13
- # --- Load and clean CSV ---
14
  def clean_df(df):
15
  df = df.copy()
16
  second_col = df.iloc[:, 2].astype(str)
17
-
18
  if second_col.str.contains('http').any() or second_col.str.contains('www').any():
19
  df["url"] = second_col
20
  else:
21
  df["url"] = "https://www.shl.com" + second_col.str.replace(r'^(?!/)', '/', regex=True)
22
-
23
  df["remote_support"] = df.iloc[:, 3].map(lambda x: "Yes" if x == "T" else "No")
24
  df["adaptive_support"] = df.iloc[:, 4].map(lambda x: "Yes" if x == "T" else "No")
25
  df["test_type"] = df.iloc[:, 5].apply(lambda x: eval(x) if isinstance(x, str) else x)
@@ -28,6 +24,7 @@ def clean_df(df):
28
 
29
  return df[["url", "adaptive_support", "remote_support", "description", "duration", "test_type"]]
30
 
 
31
  try:
32
  df = pd.read_csv("assesments.csv", encoding='utf-8')
33
  df_clean = clean_df(df)
@@ -35,7 +32,7 @@ except Exception as e:
35
  print(f"Error loading data: {e}")
36
  df_clean = pd.DataFrame(columns=["url", "adaptive_support", "remote_support", "description", "duration", "test_type"])
37
 
38
- # --- Fix URLs ---
39
  def validate_and_fix_urls(candidates):
40
  for candidate in candidates:
41
  if not isinstance(candidate, dict):
@@ -51,7 +48,7 @@ def validate_and_fix_urls(candidates):
51
  candidate['url'] = f"https://www.shl.com{url}" if url.startswith('/') else f"https://www.shl.com/{url}"
52
  return candidates
53
 
54
- # --- Recommendation Logic ---
55
  def recommend(query):
56
  if not query.strip():
57
  return {"error": "Please enter a job description"}
@@ -76,12 +73,24 @@ def recommend(query):
76
  print(traceback.format_exc())
77
  return {"error": f"Error processing request: {str(e)}"}
78
 
79
- # --- FastAPI Health Endpoint ---
 
 
 
 
 
 
 
 
 
 
 
 
80
  @app.get("/health")
81
  async def health():
82
  return JSONResponse(content={"status": "healthy"}, status_code=200)
83
 
84
- # --- FastAPI Recommendation API ---
85
  @app.post("/recommend")
86
  async def recommend_api(request: Request):
87
  try:
@@ -94,19 +103,11 @@ async def recommend_api(request: Request):
94
  except Exception as e:
95
  return JSONResponse(content={"error": str(e)}, status_code=500)
96
 
97
- # --- Gradio UI --- (integrating Gradio directly with FastAPI)
98
- def gradio_interface(query):
99
- return recommend(query)
100
-
101
- iface = gr.Interface(
102
- fn=gradio_interface,
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
- # Make sure to launch Gradio on the root path for HuggingFace Spaces
110
  @app.on_event("startup")
111
  async def startup():
 
112
  iface.launch(inline=True, server_name="0.0.0.0", server_port=7860)
 
 
1
  import pandas as pd
2
  import gradio as gr
3
  import json
4
+ from fastapi import FastAPI
5
  from fastapi.responses import JSONResponse
 
6
  from retriever import get_relevant_passages
7
  from reranker import rerank
8
 
9
+ # Load and clean CSV
 
 
 
10
  def clean_df(df):
11
  df = df.copy()
12
  second_col = df.iloc[:, 2].astype(str)
13
+
14
  if second_col.str.contains('http').any() or second_col.str.contains('www').any():
15
  df["url"] = second_col
16
  else:
17
  df["url"] = "https://www.shl.com" + second_col.str.replace(r'^(?!/)', '/', regex=True)
18
+
19
  df["remote_support"] = df.iloc[:, 3].map(lambda x: "Yes" if x == "T" else "No")
20
  df["adaptive_support"] = df.iloc[:, 4].map(lambda x: "Yes" if x == "T" else "No")
21
  df["test_type"] = df.iloc[:, 5].apply(lambda x: eval(x) if isinstance(x, str) else x)
 
24
 
25
  return df[["url", "adaptive_support", "remote_support", "description", "duration", "test_type"]]
26
 
27
+ # Load data and clean
28
  try:
29
  df = pd.read_csv("assesments.csv", encoding='utf-8')
30
  df_clean = clean_df(df)
 
32
  print(f"Error loading data: {e}")
33
  df_clean = pd.DataFrame(columns=["url", "adaptive_support", "remote_support", "description", "duration", "test_type"])
34
 
35
+ # Fix URLs
36
  def validate_and_fix_urls(candidates):
37
  for candidate in candidates:
38
  if not isinstance(candidate, dict):
 
48
  candidate['url'] = f"https://www.shl.com{url}" if url.startswith('/') else f"https://www.shl.com/{url}"
49
  return candidates
50
 
51
+ # Recommendation Logic
52
  def recommend(query):
53
  if not query.strip():
54
  return {"error": "Please enter a job description"}
 
73
  print(traceback.format_exc())
74
  return {"error": f"Error processing request: {str(e)}"}
75
 
76
+ # Initialize Gradio App
77
+ def gradio_interface(query):
78
+ return recommend(query)
79
+
80
+ iface = gr.Interface(
81
+ fn=gradio_interface,
82
+ inputs=gr.Textbox(label="Enter Job Description", lines=4),
83
+ outputs="json",
84
+ title="SHL Assessment Recommender",
85
+ description="Paste a job description to get the most relevant SHL assessments."
86
+ )
87
+
88
+ # FastAPI-like Health Endpoint in Gradio
89
  @app.get("/health")
90
  async def health():
91
  return JSONResponse(content={"status": "healthy"}, status_code=200)
92
 
93
+ # FastAPI-like Recommendation Endpoint in Gradio
94
  @app.post("/recommend")
95
  async def recommend_api(request: Request):
96
  try:
 
103
  except Exception as e:
104
  return JSONResponse(content={"error": str(e)}, status_code=500)
105
 
106
+ # Use Gradio app with the FastAPI app
107
+ app = FastAPI()
 
 
 
 
 
 
 
 
 
108
 
 
109
  @app.on_event("startup")
110
  async def startup():
111
+ # Launch Gradio app when FastAPI app starts
112
  iface.launch(inline=True, server_name="0.0.0.0", server_port=7860)
113
+