Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,11 +7,14 @@ import os
|
|
| 7 |
from fastapi import FastAPI
|
| 8 |
from pydantic import BaseModel
|
| 9 |
import uvicorn
|
|
|
|
| 10 |
|
| 11 |
# --- Configuration ---
|
| 12 |
BASE_MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
|
| 13 |
LORA_MODEL_ID = "LlamaFactoryAI/Llama-3.1-8B-Instruct-cv-job-description-matching"
|
| 14 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# --- FastAPI App ---
|
| 17 |
app = FastAPI()
|
|
@@ -24,50 +27,103 @@ class MatchRequest(BaseModel):
|
|
| 24 |
# --- Model and Tokenizer ---
|
| 25 |
model = None
|
| 26 |
tokenizer = None
|
|
|
|
| 27 |
|
| 28 |
def load_model():
|
| 29 |
-
global model, tokenizer
|
| 30 |
if model is not None:
|
| 31 |
return
|
| 32 |
-
|
| 33 |
print("Loading base model...")
|
| 34 |
-
|
|
|
|
| 35 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 36 |
BASE_MODEL_ID,
|
| 37 |
torch_dtype=torch.bfloat16,
|
| 38 |
device_map="auto",
|
| 39 |
token=HF_TOKEN
|
| 40 |
)
|
| 41 |
-
|
| 42 |
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN)
|
| 43 |
if tokenizer.pad_token is None:
|
| 44 |
tokenizer.pad_token = tokenizer.eos_token
|
| 45 |
-
|
| 46 |
print("Loading LoRA adapter...")
|
| 47 |
peft_config = PeftConfig.from_pretrained(
|
| 48 |
LORA_MODEL_ID,
|
| 49 |
task_type="CAUSAL_LM",
|
| 50 |
token=HF_TOKEN
|
| 51 |
)
|
| 52 |
-
|
| 53 |
model_with_lora = PeftModel.from_pretrained(
|
| 54 |
base_model,
|
| 55 |
LORA_MODEL_ID,
|
| 56 |
config=peft_config,
|
| 57 |
token=HF_TOKEN
|
| 58 |
)
|
| 59 |
-
|
|
|
|
| 60 |
model = model_with_lora.merge_and_unload()
|
| 61 |
model.eval()
|
| 62 |
print("Model fully loaded!")
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
# --- Core Inference ---
|
| 65 |
def match_cv_jd(cv_text: str, job_description: str) -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
if model is None or tokenizer is None:
|
| 67 |
load_model()
|
| 68 |
-
|
|
|
|
| 69 |
system_prompt = """You are a world-class CV and Job Description matching AI. Output a structured JSON with fields:- matching_analysis- description- score (0-100)- recommendation (2 concrete steps)Output MUST be valid JSON and contain ONLY the JSON object, nothing else."""
|
| 70 |
-
|
|
|
|
| 71 |
user_prompt = f"""CV:
|
| 72 |
---
|
| 73 |
{cv_text}
|
|
@@ -76,39 +132,53 @@ Job Description:
|
|
| 76 |
---
|
| 77 |
{job_description}
|
| 78 |
---"""
|
| 79 |
-
|
| 80 |
messages = [
|
| 81 |
{"role": "system", "content": system_prompt},
|
| 82 |
{"role": "user", "content": user_prompt}
|
| 83 |
]
|
| 84 |
-
|
|
|
|
| 85 |
inputs = tokenizer.apply_chat_template(
|
| 86 |
messages,
|
| 87 |
add_generation_prompt=True,
|
| 88 |
return_tensors="pt"
|
| 89 |
).to(model.device)
|
| 90 |
-
|
|
|
|
| 91 |
outputs = model.generate(
|
| 92 |
inputs,
|
| 93 |
max_new_tokens=1024,
|
| 94 |
-
temperature=0.01,
|
| 95 |
top_p=0.9,
|
| 96 |
do_sample=True,
|
| 97 |
eos_token_id=tokenizer.eos_token_id
|
| 98 |
)
|
| 99 |
-
|
|
|
|
| 100 |
response_text = tokenizer.decode(
|
| 101 |
outputs[0][inputs.shape[-1]:],
|
| 102 |
skip_special_tokens=True
|
| 103 |
).strip()
|
| 104 |
-
|
|
|
|
| 105 |
try:
|
|
|
|
| 106 |
start = response_text.find("{")
|
| 107 |
end = response_text.rfind("}")
|
| 108 |
json_str = response_text[start:end+1]
|
|
|
|
| 109 |
parsed = json.loads(json_str)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
return parsed
|
| 111 |
except Exception as e:
|
|
|
|
| 112 |
print(f"JSON Parsing failed: {e}")
|
| 113 |
return {"raw": response_text, "error": "Failed to parse JSON output from model."}
|
| 114 |
|
|
@@ -126,8 +196,10 @@ async def health_check():
|
|
| 126 |
# --- Example Data ---
|
| 127 |
EXAMPLE_CV = """**John Doe**
|
| 128 |
Email: john.doe@example.com
|
|
|
|
| 129 |
**Summary**
|
| 130 |
Experienced software engineer with 5 years in Python and backend development, specializing in building high-throughput microservices using FastAPI and Docker.
|
|
|
|
| 131 |
**Experience**
|
| 132 |
* Senior Software Engineer at TechCorp (2020-Present): Led migration of monolithic app to microservices, reducing latency by 40%.
|
| 133 |
"""
|
|
@@ -136,28 +208,31 @@ Responsibilities: Develop scalable, high-performance backend services using Pyth
|
|
| 136 |
|
| 137 |
# --- Gradio Interface ---
|
| 138 |
with gr.Blocks(title="CV & Job Matcher") as demo:
|
| 139 |
-
gr.Markdown("# CV & Job Description Matcher")
|
| 140 |
-
gr.Markdown("Enter a CV and a Job Description to get an automated match score and analysis.")
|
| 141 |
-
|
| 142 |
with gr.Row(variant="panel", equal_height=True):
|
| 143 |
cv_input = gr.Textbox(
|
| 144 |
-
label="1. Candidate CV/Resume (Text)",
|
| 145 |
-
lines=15,
|
| 146 |
-
value=EXAMPLE_CV,
|
| 147 |
interactive=True,
|
| 148 |
container=False
|
| 149 |
)
|
| 150 |
jd_input = gr.Textbox(
|
| 151 |
-
label="2. Job Description (JD) Text",
|
| 152 |
-
lines=15,
|
| 153 |
-
value=EXAMPLE_JD,
|
| 154 |
interactive=True,
|
| 155 |
container=False
|
| 156 |
)
|
| 157 |
-
|
| 158 |
-
analyze_btn = gr.Button("Analyze Match", variant="primary", scale=0)
|
|
|
|
|
|
|
| 159 |
output_display = gr.JSON(label="3. Match Output (Structured JSON Response)", scale=1)
|
| 160 |
|
|
|
|
| 161 |
analyze_btn.click(
|
| 162 |
fn=match_cv_jd,
|
| 163 |
inputs=[cv_input, jd_input],
|
|
@@ -171,4 +246,5 @@ app = gr.mount_gradio_app(app, demo, path="/")
|
|
| 171 |
# --- Launch ---
|
| 172 |
if __name__ == "__main__":
|
| 173 |
load_model()
|
|
|
|
| 174 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 7 |
from fastapi import FastAPI
|
| 8 |
from pydantic import BaseModel
|
| 9 |
import uvicorn
|
| 10 |
+
import openai # Import the OpenAI library
|
| 11 |
|
| 12 |
# --- Configuration ---
|
| 13 |
BASE_MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
|
| 14 |
LORA_MODEL_ID = "LlamaFactoryAI/Llama-3.1-8B-Instruct-cv-job-description-matching"
|
| 15 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 16 |
+
# NEW: Check for OpenAI API key
|
| 17 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 18 |
|
| 19 |
# --- FastAPI App ---
|
| 20 |
app = FastAPI()
|
|
|
|
| 27 |
# --- Model and Tokenizer ---
|
| 28 |
model = None
|
| 29 |
tokenizer = None
|
| 30 |
+
openai_client = None
|
| 31 |
|
| 32 |
def load_model():
|
| 33 |
+
global model, tokenizer, openai_client
|
| 34 |
if model is not None:
|
| 35 |
return
|
| 36 |
+
|
| 37 |
print("Loading base model...")
|
| 38 |
+
|
| 39 |
+
# Load base model
|
| 40 |
base_model = AutoModelForCausalLM.from_pretrained(
|
| 41 |
BASE_MODEL_ID,
|
| 42 |
torch_dtype=torch.bfloat16,
|
| 43 |
device_map="auto",
|
| 44 |
token=HF_TOKEN
|
| 45 |
)
|
| 46 |
+
|
| 47 |
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN)
|
| 48 |
if tokenizer.pad_token is None:
|
| 49 |
tokenizer.pad_token = tokenizer.eos_token
|
| 50 |
+
|
| 51 |
print("Loading LoRA adapter...")
|
| 52 |
peft_config = PeftConfig.from_pretrained(
|
| 53 |
LORA_MODEL_ID,
|
| 54 |
task_type="CAUSAL_LM",
|
| 55 |
token=HF_TOKEN
|
| 56 |
)
|
| 57 |
+
|
| 58 |
model_with_lora = PeftModel.from_pretrained(
|
| 59 |
base_model,
|
| 60 |
LORA_MODEL_ID,
|
| 61 |
config=peft_config,
|
| 62 |
token=HF_TOKEN
|
| 63 |
)
|
| 64 |
+
|
| 65 |
+
# Merge the LoRA adapter into the base model for a single, faster inference model
|
| 66 |
model = model_with_lora.merge_and_unload()
|
| 67 |
model.eval()
|
| 68 |
print("Model fully loaded!")
|
| 69 |
|
| 70 |
+
# Initialize OpenAI client if key is available
|
| 71 |
+
if OPENAI_API_KEY:
|
| 72 |
+
openai_client = openai.OpenAI(api_key=OPENAI_API_KEY)
|
| 73 |
+
print("OpenAI client initialized.")
|
| 74 |
+
else:
|
| 75 |
+
print("OPENAI_API_KEY not found. Skipping human-readable summary generation.")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def get_human_readable_summary(json_data: dict) -> str:
|
| 79 |
+
"""Uses OpenAI to convert structured JSON data into human-readable text."""
|
| 80 |
+
if not openai_client:
|
| 81 |
+
return "OpenAI API not available. Set OPENAI_API_KEY to enable summarization."
|
| 82 |
+
|
| 83 |
+
# Defining a prompt to achieve the conversion to human-readable text
|
| 84 |
+
prompt = f"""
|
| 85 |
+
You are an expert technical writer. Take the following structured JSON data
|
| 86 |
+
representing a CV-Job Description match analysis and convert it into a smooth,
|
| 87 |
+
professional, human-readable summary. Focus on the score, key findings in
|
| 88 |
+
'matching_analysis' and 'description', and format the 'recommendation'
|
| 89 |
+
steps clearly at the end. Do not output any JSON or code formatting.
|
| 90 |
+
|
| 91 |
+
JSON Data:
|
| 92 |
+
---
|
| 93 |
+
{json.dumps(json_data, indent=2)}
|
| 94 |
+
---
|
| 95 |
+
|
| 96 |
+
Human-Readable Summary:
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
completion = openai_client.chat.completions.create(
|
| 101 |
+
model="gpt-4o-mini", # A fast and capable model for this task
|
| 102 |
+
messages=[
|
| 103 |
+
{"role": "user", "content": prompt}
|
| 104 |
+
],
|
| 105 |
+
temperature=0.2, # Low temperature for reliable summarization
|
| 106 |
+
)
|
| 107 |
+
return completion.choices[0].message.content.strip()
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"OpenAI API call failed: {e}")
|
| 110 |
+
return f"OpenAI summarization failed due to an API error: {e}"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
# --- Core Inference ---
|
| 114 |
def match_cv_jd(cv_text: str, job_description: str) -> dict:
|
| 115 |
+
"""
|
| 116 |
+
Performs the CV-JD matching using the merged Llama 3.1 model and post-processes
|
| 117 |
+
the result using OpenAI if available.
|
| 118 |
+
"""
|
| 119 |
+
# Ensure model is loaded (important for environments where Gradio might reload)
|
| 120 |
if model is None or tokenizer is None:
|
| 121 |
load_model()
|
| 122 |
+
|
| 123 |
+
# System prompt guides the model's behavior and output format (JSON structure)
|
| 124 |
system_prompt = """You are a world-class CV and Job Description matching AI. Output a structured JSON with fields:- matching_analysis- description- score (0-100)- recommendation (2 concrete steps)Output MUST be valid JSON and contain ONLY the JSON object, nothing else."""
|
| 125 |
+
|
| 126 |
+
# User prompt contains the input data
|
| 127 |
user_prompt = f"""CV:
|
| 128 |
---
|
| 129 |
{cv_text}
|
|
|
|
| 132 |
---
|
| 133 |
{job_description}
|
| 134 |
---"""
|
| 135 |
+
|
| 136 |
messages = [
|
| 137 |
{"role": "system", "content": system_prompt},
|
| 138 |
{"role": "user", "content": user_prompt}
|
| 139 |
]
|
| 140 |
+
|
| 141 |
+
# Prepare inputs for the model
|
| 142 |
inputs = tokenizer.apply_chat_template(
|
| 143 |
messages,
|
| 144 |
add_generation_prompt=True,
|
| 145 |
return_tensors="pt"
|
| 146 |
).to(model.device)
|
| 147 |
+
|
| 148 |
+
# Generate the response
|
| 149 |
outputs = model.generate(
|
| 150 |
inputs,
|
| 151 |
max_new_tokens=1024,
|
| 152 |
+
temperature=0.01, # Keep temperature low for structured/deterministic output
|
| 153 |
top_p=0.9,
|
| 154 |
do_sample=True,
|
| 155 |
eos_token_id=tokenizer.eos_token_id
|
| 156 |
)
|
| 157 |
+
|
| 158 |
+
# Decode the response and clean up
|
| 159 |
response_text = tokenizer.decode(
|
| 160 |
outputs[0][inputs.shape[-1]:],
|
| 161 |
skip_special_tokens=True
|
| 162 |
).strip()
|
| 163 |
+
|
| 164 |
+
# Attempt to parse the JSON output
|
| 165 |
try:
|
| 166 |
+
# Robustly find the start and end of the JSON object in the response
|
| 167 |
start = response_text.find("{")
|
| 168 |
end = response_text.rfind("}")
|
| 169 |
json_str = response_text[start:end+1]
|
| 170 |
+
|
| 171 |
parsed = json.loads(json_str)
|
| 172 |
+
|
| 173 |
+
# --- NEW: Post-process with OpenAI to add human_readable summary ---
|
| 174 |
+
if OPENAI_API_KEY and openai_client:
|
| 175 |
+
human_readable_text = get_human_readable_summary(parsed)
|
| 176 |
+
# Add the summary to the JSON output
|
| 177 |
+
parsed["human_readable"] = human_readable_text
|
| 178 |
+
|
| 179 |
return parsed
|
| 180 |
except Exception as e:
|
| 181 |
+
# Fallback for poorly formed output
|
| 182 |
print(f"JSON Parsing failed: {e}")
|
| 183 |
return {"raw": response_text, "error": "Failed to parse JSON output from model."}
|
| 184 |
|
|
|
|
| 196 |
# --- Example Data ---
|
| 197 |
EXAMPLE_CV = """**John Doe**
|
| 198 |
Email: john.doe@example.com
|
| 199 |
+
|
| 200 |
**Summary**
|
| 201 |
Experienced software engineer with 5 years in Python and backend development, specializing in building high-throughput microservices using FastAPI and Docker.
|
| 202 |
+
|
| 203 |
**Experience**
|
| 204 |
* Senior Software Engineer at TechCorp (2020-Present): Led migration of monolithic app to microservices, reducing latency by 40%.
|
| 205 |
"""
|
|
|
|
| 208 |
|
| 209 |
# --- Gradio Interface ---
|
| 210 |
with gr.Blocks(title="CV & Job Matcher") as demo:
|
| 211 |
+
gr.Markdown("# 🤖 CV & Job Description Matcher")
|
| 212 |
+
gr.Markdown("Enter a CV and a Job Description to get an automated match score and analysis using a fine-tuned Llama 3.1 model.")
|
| 213 |
+
|
| 214 |
with gr.Row(variant="panel", equal_height=True):
|
| 215 |
cv_input = gr.Textbox(
|
| 216 |
+
label="1. Candidate CV/Resume (Text)",
|
| 217 |
+
lines=15,
|
| 218 |
+
value=EXAMPLE_CV,
|
| 219 |
interactive=True,
|
| 220 |
container=False
|
| 221 |
)
|
| 222 |
jd_input = gr.Textbox(
|
| 223 |
+
label="2. Job Description (JD) Text",
|
| 224 |
+
lines=15,
|
| 225 |
+
value=EXAMPLE_JD,
|
| 226 |
interactive=True,
|
| 227 |
container=False
|
| 228 |
)
|
| 229 |
+
|
| 230 |
+
analyze_btn = gr.Button("🚀 Analyze Match", variant="primary", scale=0)
|
| 231 |
+
|
| 232 |
+
# The output component for the structured JSON response
|
| 233 |
output_display = gr.JSON(label="3. Match Output (Structured JSON Response)", scale=1)
|
| 234 |
|
| 235 |
+
# Internal UI Click & External API Access (combined for compatibility)
|
| 236 |
analyze_btn.click(
|
| 237 |
fn=match_cv_jd,
|
| 238 |
inputs=[cv_input, jd_input],
|
|
|
|
| 246 |
# --- Launch ---
|
| 247 |
if __name__ == "__main__":
|
| 248 |
load_model()
|
| 249 |
+
# Use uvicorn to run the FastAPI app, which hosts the Gradio interface
|
| 250 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|