Download app.py from MBG0903/Procelevate-TalentMatch-AI: direct link, hf CLI and curl.
- Browser
- Download file 28.6 kB
-
https://huggingface.co/spaces/MBG0903/Procelevate-TalentMatch-AI/resolve/main/app.py
- Command line
-
hf download hf://spaces/MBG0903/Procelevate-TalentMatch-AI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MBG0903/Procelevate-TalentMatch-AI/resolve/main/app.py
28.6 kB
import os
import json
import re
import tempfile
from typing import Dict, Any
import pandas as pd
import gradio as gr
import PyPDF2
from huggingface_hub import InferenceClient
# =========================
# Config
# =========================
APP_TITLE = "Procelevate TalentMatch AI"
APP_SUBTITLE = "Agentic AI for Data Analyst / Data Engineering Candidate Screening"
PROCELEVATE_BLUE = "#0F2C59"
MAX_RESUMES = 5
# Hugging Face configuration
HF_TOKEN = os.getenv("Talent_Search_AI")
HF_MODEL = os.getenv("HF_MODEL", "Qwen/Qwen2.5-7B-Instruct")
hf_client = InferenceClient(
model=HF_MODEL,
token=HF_TOKEN,
) if HF_TOKEN else None
DEFAULT_JD = """Role: Data Analyst / Data Engineer
We are looking for candidates with experience in SQL, Python, data visualization,
ETL pipelines, data cleaning, dashboarding, and cloud data platforms.
Exposure to Power BI, Tableau, Azure, AWS, Snowflake, Airflow, or Spark is preferred.
Responsibilities:
- Analyze large datasets and generate insights
- Build and maintain data pipelines
- Create dashboards and business reports
- Work with stakeholders to gather requirements
- Ensure data quality and governance
Preferred:
- 3+ years of experience
- Strong communication skills
- Experience in analytics and engineering environments
"""
# =========================
# Utility Functions
# =========================
def clean_text(text: str) -> str:
if not text:
return ""
return re.sub(r"\s+", " ", text).strip()
def read_pdf(file_path: str) -> str:
text = ""
try:
with open(file_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
for page in reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
except Exception as e:
return f"Error reading PDF: {str(e)}"
text = clean_text(text)
if not text:
return (
"Error reading PDF: No machine-readable text was found. "
"This PDF may be image-based/scanned."
)
return text
def read_txt(file_path: str) -> str:
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
return clean_text(f.read())
except Exception as e:
return f"Error reading TXT: {str(e)}"
def file_to_text(file_obj) -> str:
if file_obj is None:
return ""
file_path = file_obj if isinstance(file_obj, str) else file_obj.name
lower = file_path.lower()
if lower.endswith(".pdf"):
return read_pdf(file_path)
elif lower.endswith(".txt"):
return read_txt(file_path)
else:
return "Unsupported file format. Please upload PDF or TXT."
def extract_json_object(text: str) -> Dict[str, Any]:
"""
Robustly extract JSON even if the model wraps it in markdown fences.
"""
if not text:
return {"error": "The model returned an empty response."}
text = text.strip()
# Remove ```json ... ``` or ``` ... ```
if text.startswith("```"):
text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE)
text = re.sub(r"\s*```$", "", text)
try:
return json.loads(text)
except Exception:
pass
# Fall back to the first top-level-looking JSON object
match = re.search(r"\{.*\}", text, flags=re.DOTALL)
if match:
try:
return json.loads(match.group(0))
except Exception as e:
return {
"error": f"Model returned text that could not be parsed as JSON: {str(e)}",
"raw_response": text[:1200],
}
return {
"error": "Model response did not contain a valid JSON object.",
"raw_response": text[:1200],
}
def call_llm_json(
system_prompt: str,
user_prompt: str,
max_tokens: int = 1200
) -> Dict[str, Any]:
"""
Calls a Hugging Face hosted instruction model and returns parsed JSON.
"""
if not hf_client:
return {
"error": (
"HF_TOKEN is not set. Add your Hugging Face token "
"to the Space Secrets."
)
}
try:
response = hf_client.chat_completion(
messages=[
{
"role": "system",
"content": (
system_prompt
+ "\nIMPORTANT: Return exactly one valid JSON object. "
"Do not use markdown fences or add commentary."
),
},
{"role": "user", "content": user_prompt},
],
max_tokens=max_tokens,
temperature=0.2,
)
content = response.choices[0].message.content
return extract_json_object(content)
except Exception as e:
return {
"error": (
f"Hugging Face inference failed using model '{HF_MODEL}': {str(e)}"
)
}
def safe_list_to_text(value) -> str:
if isinstance(value, list):
return ", ".join(str(v) for v in value)
if value is None:
return ""
return str(value)
def get_decision_band(recommendation: str) -> str:
rec = (recommendation or "").strip().lower()
if rec == "shortlist":
return "Green"
elif rec == "hold":
return "Amber"
elif rec == "reject":
return "Red"
return "Review"
def build_candidate_detail(record: Dict[str, Any]) -> str:
return f"""
### Candidate Detail Review
**Candidate:** {record.get('Candidate', '')}
**Current Role:** {record.get('Current Role', '')}
**Experience:** {record.get('Experience (Yrs)', '')} years
**Location:** {record.get('Location', '')}
**Role Fit:** {record.get('Role Fit', '')}
**Match Score:** {record.get('Match Score', '')}
**Recommendation:** {record.get('Recommendation', '')}
**Decision Band:** {record.get('Decision Band', '')}
---
**Why Selected**
{record.get('Why Selected', '')}
**Matched Skills**
{record.get('Matched Skills', '')}
**Missing Skills / Gaps**
{record.get('Missing Skills / Gaps', '')}
**Interview Focus Areas**
{record.get('Interview Focus Areas', '')}
**Recommended HR Action**
{record.get('Recommended HR Action', '')}
**Outreach Message**
{record.get('Outreach Message', '')}
**Response Intent**
{record.get('Response Intent', '')}
**Final Status**
{record.get('Final Status', '')}
**Next Step**
{record.get('Next Step', '')}
**Bias-Safe Review Note**
{record.get('Bias-Safe Review Note', '')}
"""
# =========================
# Agent Functions
# =========================
def resume_intake_agent(resume_text: str) -> Dict[str, Any]:
system_prompt = """
You are Resume Intake Agent, an HR talent-screening assistant.
Extract only information explicitly supported by the resume.
Do not infer protected or sensitive personal attributes.
If a field is unavailable, use an empty string or empty list.
"""
user_prompt = f"""
Extract the following candidate information from the resume.
Return JSON with exactly these keys:
{{
"candidate_name": "",
"email": "",
"phone": "",
"current_location": "",
"total_experience_years": "",
"current_role": "",
"current_company": "",
"skills": [],
"tools_technologies": [],
"education": [],
"certifications": [],
"projects_summary": "",
"relevant_data_analyst_experience": "",
"relevant_data_engineering_experience": "",
"likely_notice_period": "",
"summary": ""
}}
Rules:
- Do not invent experience, skills, employers, notice period, or qualifications.
- If notice period is not explicitly stated, return "".
- Keep lists concise.
Resume Text:
{resume_text}
"""
return call_llm_json(system_prompt, user_prompt, max_tokens=1400)
def jd_matching_agent(
jd_text: str,
candidate_profile: Dict[str, Any]
) -> Dict[str, Any]:
system_prompt = """
You are JD Matching Agent.
Evaluate a candidate only against job-related requirements.
Use skills, relevant experience, tools, responsibilities, and qualifications.
Do not consider protected or sensitive personal attributes.
Be explainable and conservative.
"""
user_prompt = f"""
Compare the candidate profile against the Job Description.
Job Description:
{jd_text}
Candidate Profile:
{json.dumps(candidate_profile, indent=2)}
Return JSON:
{{
"role_fit": "Data Analyst / Data Engineer / Both / Low Fit",
"match_score": 0,
"matched_skills": [],
"missing_skills": [],
"why_selected": [],
"interview_focus_areas": [],
"recommended_hr_action": "",
"bias_safe_review_note": ""
}}
Scoring guidance:
- 80-100: strong alignment
- 60-79: partial/moderate alignment
- below 60: weak alignment
Important:
- Score only from evidence in the candidate profile and JD.
- Missing information is not evidence of capability.
- Do not invent candidate experience.
- Keep matched/missing skill lists focused on important JD requirements.
"""
return call_llm_json(system_prompt, user_prompt, max_tokens=1300)
def outreach_agent(
candidate_name: str,
role_title: str,
recommendation: str
) -> Dict[str, Any]:
system_prompt = """
You are Candidate Outreach Agent.
Create concise, professional recruiter outreach.
Avoid promises about hiring outcomes.
"""
user_prompt = f"""
Candidate Name: {candidate_name}
Role Title: {role_title}
Screening Recommendation: {recommendation}
Return JSON:
{{
"whatsapp_message": "",
"email_message": ""
}}
Keep the messages professional and short.
"""
return call_llm_json(system_prompt, user_prompt, max_tokens=500)
def response_classifier_agent(candidate_response: str) -> Dict[str, Any]:
"""
Lightweight rule-based classifier for the simulated demo response.
This avoids spending an additional LLM inference call on predictable text.
"""
text = (candidate_response or "").lower().strip()
if not text:
intent = "Unclear"
summary = "No response received."
next_action = "Follow up later if appropriate."
elif any(
phrase in text
for phrase in [
"not interested",
"not looking",
"no thanks",
"decline",
]
):
intent = "Not Interested"
summary = "Candidate is currently not interested in pursuing the opportunity."
next_action = "Close or retain the profile for future relevant opportunities."
elif any(
phrase in text
for phrase in [
"more details",
"share details",
"tell me more",
"role details",
]
):
intent = "Needs More Information"
summary = "Candidate requested additional information about the opportunity."
next_action = "Share the role details and answer candidate questions."
elif any(
phrase in text
for phrase in [
"later",
"next month",
"after",
"currently busy",
]
):
intent = "Available Later"
summary = "Candidate may be open to discussion at a later date."
next_action = "Schedule an appropriate follow-up."
elif any(
phrase in text
for phrase in [
"interested",
"available",
"discuss",
"yes",
]
):
intent = "Interested"
summary = "Candidate expressed interest in discussing the opportunity."
next_action = "Proceed to recruiter screening or interview scheduling."
else:
intent = "Unclear"
summary = "Candidate intent could not be confidently determined."
next_action = "Request clarification from the candidate."
return {
"intent": intent,
"summary": summary,
"recommended_next_action": next_action,
}
def hr_summary_agent(
candidate_profile: Dict[str, Any],
match_result: Dict[str, Any],
response_result: Dict[str, Any],
recommendation: str,
) -> Dict[str, Any]:
system_prompt = """
You are HR Summary Agent.
Prepare a concise recruiter-ready briefing for human review.
Do not make the final hiring decision.
Use only supplied evidence.
"""
user_prompt = f"""
Candidate Profile:
{json.dumps(candidate_profile, indent=2)}
JD Match Result:
{json.dumps(match_result, indent=2)}
Candidate Response Result:
{json.dumps(response_result, indent=2)}
System Recommendation:
{recommendation}
Return JSON:
{{
"final_status": "",
"recruiter_summary": "",
"interview_readiness": "",
"recommended_next_step": "",
"recruiter_action_pack": []
}}
The final_status should describe workflow status, not a final employment decision.
"""
return call_llm_json(system_prompt, user_prompt, max_tokens=800)
# =========================
# Main Workflow
# =========================
def run_talentmatch(role_title: str, jd_text: str, resume_files):
try:
if not HF_TOKEN:
error_df = pd.DataFrame(
[{"Error": "HF_TOKEN is not set in Hugging Face Space Secrets."}]
)
return (
error_df,
"HF_TOKEN is not set.",
gr.Dropdown(choices=[], value=None),
"Please configure HF_TOKEN in Hugging Face Space Secrets.",
None,
{},
)
if not jd_text or not jd_text.strip():
error_df = pd.DataFrame(
[{"Error": "Please paste or keep the default Job Description."}]
)
return (
error_df,
"Please paste or keep the default Job Description.",
gr.Dropdown(choices=[], value=None),
"Please provide a Job Description.",
None,
{},
)
if not resume_files:
error_df = pd.DataFrame(
[{"Error": "Please upload at least one resume."}]
)
return (
error_df,
"Please upload at least one resume.",
gr.Dropdown(choices=[], value=None),
"Please upload at least one resume.",
None,
{},
)
if len(resume_files) > MAX_RESUMES:
error_df = pd.DataFrame(
[{
"Error": (
f"Please upload maximum {MAX_RESUMES} resumes per run "
"for optimal performance."
)
}]
)
return (
error_df,
f"Please upload maximum {MAX_RESUMES} resumes per run.",
gr.Dropdown(choices=[], value=None),
f"Reduce the uploaded resumes to {MAX_RESUMES} or fewer.",
None,
{},
)
records = []
for file_obj in resume_files:
file_name = (
file_obj
if isinstance(file_obj, str)
else getattr(file_obj, "name", "resume")
)
resume_text = file_to_text(file_obj)
if resume_text.startswith("Error"):
raise Exception(
f"Resume read failed for {file_name}: {resume_text}"
)
# -----------------------------
# Agent 1: Resume Intake
# -----------------------------
candidate_profile = resume_intake_agent(resume_text)
if "error" in candidate_profile:
raise Exception(
f"Resume Intake Agent failed for {file_name}: "
f"{candidate_profile['error']}"
)
# -----------------------------
# Agent 2: JD Matching
# -----------------------------
match_result = jd_matching_agent(jd_text, candidate_profile)
if "error" in match_result:
raise Exception(
f"JD Matching Agent failed for {file_name}: "
f"{match_result['error']}"
)
candidate_name = (
candidate_profile.get("candidate_name")
or os.path.basename(file_name)
.replace(".pdf", "")
.replace(".txt", "")
)
# -----------------------------
# Deterministic Decision Engine
# -----------------------------
raw_score = match_result.get("match_score", 0)
try:
score = float(raw_score)
except Exception:
score = 0.0
# Keep score in valid range
score = max(0.0, min(100.0, score))
if score >= 80:
recommendation = "Shortlist"
elif score >= 60:
recommendation = "Hold"
else:
recommendation = "Reject"
match_result["recommendation"] = recommendation
# -----------------------------
# Agent 3: Outreach
# -----------------------------
outreach = outreach_agent(
candidate_name,
role_title,
recommendation,
)
if "error" in outreach:
raise Exception(
f"Outreach Agent failed for {file_name}: "
f"{outreach['error']}"
)
# -----------------------------
# Demo Candidate Response
# -----------------------------
if recommendation == "Shortlist":
simulated_response = (
"Yes, I am interested and available to discuss "
"this opportunity further."
)
elif recommendation == "Hold":
simulated_response = (
"Please share more details about the role, "
"team structure, and work location."
)
else:
simulated_response = (
"Thank you for reaching out. "
"I am currently not looking for a change."
)
# -----------------------------
# Agent 4: Response Classifier
# Rule-based for demo efficiency
# -----------------------------
response_result = response_classifier_agent(
simulated_response
)
# -----------------------------
# Agent 5: HR Summary
# -----------------------------
hr_summary = hr_summary_agent(
candidate_profile,
match_result,
response_result,
recommendation,
)
if "error" in hr_summary:
raise Exception(
f"HR Summary Agent failed for {file_name}: "
f"{hr_summary['error']}"
)
decision_band = get_decision_band(recommendation)
outreach_message = (
outreach.get("whatsapp_message")
or outreach.get("email_message")
or ""
)
record = {
"Candidate": candidate_name,
"Current Role": candidate_profile.get(
"current_role", ""
),
"Experience (Yrs)": candidate_profile.get(
"total_experience_years", ""
),
"Location": candidate_profile.get(
"current_location", ""
),
"Role Fit": match_result.get("role_fit", ""),
"Match Score": score,
"Recommendation": recommendation,
"Decision Band": decision_band,
"Why Selected": safe_list_to_text(
match_result.get("why_selected", [])
),
"Matched Skills": safe_list_to_text(
match_result.get("matched_skills", [])
),
"Missing Skills / Gaps": safe_list_to_text(
match_result.get("missing_skills", [])
),
"Interview Focus Areas": safe_list_to_text(
match_result.get("interview_focus_areas", [])
),
"Recommended HR Action": match_result.get(
"recommended_hr_action", ""
),
"Outreach Message": outreach_message,
"Response Intent": response_result.get(
"intent", ""
),
"Final Status": hr_summary.get(
"final_status", ""
),
"Next Step": hr_summary.get(
"recommended_next_step", ""
),
"Bias-Safe Review Note": match_result.get(
"bias_safe_review_note",
(
"Recommendation is based on job-related "
"skills, experience, tools, and role fit only."
),
),
}
records.append(record)
full_df = pd.DataFrame(records)
compact_columns = [
"Candidate",
"Current Role",
"Experience (Yrs)",
"Role Fit",
"Match Score",
"Recommendation",
"Decision Band",
]
compact_df = full_df[compact_columns].copy()
avg_score = (
round(
pd.to_numeric(
full_df["Match Score"],
errors="coerce",
).fillna(0).mean(),
1,
)
if len(full_df)
else 0
)
shortlisted = int(
(full_df["Recommendation"] == "Shortlist").sum()
)
hold_count = int(
(full_df["Recommendation"] == "Hold").sum()
)
reject_count = int(
(full_df["Recommendation"] == "Reject").sum()
)
summary_text = (
f"Model: {HF_MODEL}\n"
f"Total Candidates: {len(full_df)}\n"
f"Shortlisted: {shortlisted}\n"
f"Hold: {hold_count}\n"
f"Rejected: {reject_count}\n"
f"Average Match Score: {avg_score}\n\n"
f"Decision Band Logic:\n"
f"- Green = Shortlist\n"
f"- Amber = Hold\n"
f"- Red = Reject"
)
csv_path = os.path.join(
tempfile.gettempdir(),
"talentmatch_screening_results.csv",
)
full_df.to_csv(csv_path, index=False)
candidate_choices = full_df["Candidate"].tolist()
default_candidate = (
candidate_choices[0]
if candidate_choices
else None
)
first_record = records[0] if records else {}
detail_markdown = (
build_candidate_detail(first_record)
if first_record
else "No candidate details available."
)
# Duplicate candidate names could collide, so make keys unique.
state_data = {}
unique_choices = []
for idx, record in enumerate(records, start=1):
base_name = record["Candidate"] or f"Candidate {idx}"
display_name = base_name
if display_name in state_data:
display_name = f"{base_name} ({idx})"
state_data[display_name] = record
unique_choices.append(display_name)
default_candidate = (
unique_choices[0]
if unique_choices
else None
)
return (
compact_df,
summary_text,
gr.Dropdown(
choices=unique_choices,
value=default_candidate,
),
detail_markdown,
csv_path,
state_data,
)
except Exception as e:
error_message = f"Workflow failed: {str(e)}"
error_df = pd.DataFrame(
[{"Error": error_message}]
)
return (
error_df,
error_message,
gr.Dropdown(choices=[], value=None),
error_message,
None,
{},
)
def update_candidate_detail(
selected_candidate,
state_data,
):
if not selected_candidate or not state_data:
return "No candidate selected."
record = state_data.get(selected_candidate)
if not record:
return "Candidate details not found."
return build_candidate_detail(record)
# =========================
# UI Styling
# =========================
custom_css = f"""
body {{
background: white;
}}
h1, h2, h3 {{
color: {PROCELEVATE_BLUE} !important;
}}
.gradio-container {{
max-width: 1320px !important;
}}
.procelevate-header {{
text-align: center;
margin-bottom: 10px;
}}
.notice-box {{
border: 1px solid #d9e2f0;
background: #f8fbff;
border-radius: 12px;
padding: 14px;
margin-top: 8px;
margin-bottom: 16px;
}}
"""
# =========================
# Gradio App
# =========================
with gr.Blocks(css=custom_css, title=APP_TITLE) as demo:
state_store = gr.State({})
gr.HTML(
f"""
<div class="procelevate-header">
<h1>{APP_TITLE}</h1>
<h3>{APP_SUBTITLE}</h3>
</div>
<div class="notice-box">
<b>Prototype Scope:</b>
This demo shows how Agentic AI can support HR teams by parsing resumes,
matching profiles to a job description, generating shortlist recommendations,
drafting outreach, interpreting candidate responses, and preparing recruiter-ready summaries.
<br><br>
<b>AI Provider:</b>
Hugging Face hosted inference using <b>{HF_MODEL}</b>.
<br><br>
<b>Enterprise Upgrade:</b>
This version adds explainability, interview focus guidance,
decision bands, HR action recommendations, and a bias-safe review note.
<br><br>
<b>Important:</b>
This is a decision-support system. Final hiring decisions remain with HR.
<br><br>
<b>Usage Note:</b>
Upload up to {MAX_RESUMES} resumes per run for stable demo performance.
</div>
"""
)
with gr.Row():
with gr.Column(scale=2):
role_title = gr.Textbox(
label="Role Title",
value="Data Analyst / Data Engineer",
placeholder="Enter target role",
)
jd_text = gr.Textbox(
label="Paste Job Description",
lines=14,
value=DEFAULT_JD,
placeholder="Paste the JD here...",
)
resume_files = gr.File(
label="Upload Candidate Resumes (PDF or TXT)",
file_count="multiple",
file_types=[".pdf", ".txt"],
)
run_button = gr.Button(
"Run TalentMatch Workflow",
variant="primary",
)
with gr.Column(scale=1):
output_summary = gr.Textbox(
label="Screening Summary",
lines=12,
)
output_file = gr.File(
label="Download Screening Results CSV",
visible=True,
)
output_df = gr.Dataframe(
label="Candidate Screening Dashboard",
interactive=False,
)
gr.Markdown("### Candidate Review Detail")
candidate_selector = gr.Dropdown(
label="Select Candidate",
choices=[],
value=None,
)
candidate_detail = gr.Markdown(
"Run the workflow to view candidate details."
)
run_button.click(
fn=run_talentmatch,
inputs=[
role_title,
jd_text,
resume_files,
],
outputs=[
output_df,
output_summary,
candidate_selector,
candidate_detail,
output_file,
state_store,
],
)
candidate_selector.change(
fn=update_candidate_detail,
inputs=[
candidate_selector,
state_store,
],
outputs=[candidate_detail],
)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=7860,
)
import os
import json
import re
import tempfile
from typing import Dict, Any
import pandas as pd
import gradio as gr
import PyPDF2
from huggingface_hub import InferenceClient
# =========================
# Config
# =========================
APP_TITLE = "Procelevate TalentMatch AI"
APP_SUBTITLE = "Agentic AI for Data Analyst / Data Engineering Candidate Screening"
PROCELEVATE_BLUE = "#0F2C59"
MAX_RESUMES = 5
# Hugging Face configuration
HF_TOKEN = os.getenv("Talent_Search_AI")
HF_MODEL = os.getenv("HF_MODEL", "Qwen/Qwen2.5-7B-Instruct")
hf_client = InferenceClient(
model=HF_MODEL,
token=HF_TOKEN,
) if HF_TOKEN else None
DEFAULT_JD = """Role: Data Analyst / Data Engineer
We are looking for candidates with experience in SQL, Python, data visualization,
ETL pipelines, data cleaning, dashboarding, and cloud data platforms.
Exposure to Power BI, Tableau, Azure, AWS, Snowflake, Airflow, or Spark is preferred.
Responsibilities:
- Analyze large datasets and generate insights
- Build and maintain data pipelines
- Create dashboards and business reports
- Work with stakeholders to gather requirements
- Ensure data quality and governance
Preferred:
- 3+ years of experience
- Strong communication skills
- Experience in analytics and engineering environments
"""
# =========================
# Utility Functions
# =========================
def clean_text(text: str) -> str:
if not text:
return ""
return re.sub(r"\s+", " ", text).strip()
def read_pdf(file_path: str) -> str:
text = ""
try:
with open(file_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
for page in reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
except Exception as e:
return f"Error reading PDF: {str(e)}"
text = clean_text(text)
if not text:
return (
"Error reading PDF: No machine-readable text was found. "
"This PDF may be image-based/scanned."
)
return text
def read_txt(file_path: str) -> str:
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
return clean_text(f.read())
except Exception as e:
return f"Error reading TXT: {str(e)}"
def file_to_text(file_obj) -> str:
if file_obj is None:
return ""
file_path = file_obj if isinstance(file_obj, str) else file_obj.name
lower = file_path.lower()
if lower.endswith(".pdf"):
return read_pdf(file_path)
elif lower.endswith(".txt"):