mployd-engineering commited on
Commit
8c6d65a
·
verified ·
1 Parent(s): db08d2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -32
app.py CHANGED
@@ -18,51 +18,55 @@ def load_model():
18
  global model, tokenizer
19
  if model is not None:
20
  return
21
-
22
  print("Loading base model...")
 
23
  # Load base model
 
24
  base_model = AutoModelForCausalLM.from_pretrained(
25
  BASE_MODEL_ID,
26
  torch_dtype=torch.bfloat16,
27
  device_map="auto",
28
  token=HF_TOKEN
29
  )
30
-
31
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN)
32
  if tokenizer.pad_token is None:
33
  tokenizer.pad_token = tokenizer.eos_token
34
-
35
  print("Loading LoRA adapter...")
36
  peft_config = PeftConfig.from_pretrained(
37
  LORA_MODEL_ID,
38
  task_type="CAUSAL_LM",
39
  token=HF_TOKEN
40
  )
41
-
42
  model_with_lora = PeftModel.from_pretrained(
43
  base_model,
44
  LORA_MODEL_ID,
45
  config=peft_config,
46
  token=HF_TOKEN
47
  )
48
-
 
49
  model = model_with_lora.merge_and_unload()
50
  model.eval()
51
  print("Model fully loaded!")
52
 
53
  # --- Core Inference ---
 
54
  def match_cv_jd(cv_text: str, job_description: str) -> dict:
55
- # Ensure model is loaded if running in a context where global init failed
 
 
 
56
  if model is None or tokenizer is None:
57
  load_model()
58
-
59
- system_prompt = """You are a world-class CV and Job Description matching AI. Output a structured JSON with fields:
60
- - matching_analysis
61
- - description
62
- - score (0-100)
63
- - recommendation (2 concrete steps)
64
- Output MUST be valid JSON."""
65
-
66
  user_prompt = f"""CV:
67
  ---
68
  {cv_text}
@@ -71,72 +75,101 @@ Job Description:
71
  ---
72
  {job_description}
73
  ---"""
74
-
75
  messages = [
76
  {"role": "system", "content": system_prompt},
77
  {"role": "user", "content": user_prompt}
78
  ]
79
-
 
80
  inputs = tokenizer.apply_chat_template(
81
  messages,
82
  add_generation_prompt=True,
83
  return_tensors="pt"
84
  ).to(model.device)
85
-
 
86
  outputs = model.generate(
87
  inputs,
88
  max_new_tokens=1024,
89
- temperature=0.01,
90
  top_p=0.9,
91
  do_sample=True,
92
  eos_token_id=tokenizer.eos_token_id
93
  )
94
-
 
95
  response_text = tokenizer.decode(
96
  outputs[0][inputs.shape[-1]:],
97
  skip_special_tokens=True
98
  ).strip()
99
-
 
100
  try:
 
101
  start = response_text.find("{")
102
  end = response_text.rfind("}")
103
  json_str = response_text[start:end+1]
 
104
  parsed = json.loads(json_str)
105
  return parsed
106
- except:
107
- return {"raw": response_text}
 
 
108
 
109
  # --- Example Data ---
110
  EXAMPLE_CV = """**John Doe**
111
  Email: john.doe@example.com
 
112
  **Summary**
113
- Experienced software engineer with 5 years in Python and backend development."""
114
 
 
 
 
115
  EXAMPLE_JD = """**Job Title: Senior Backend Engineer**
116
- Responsibilities: Develop scalable backend services using Python."""
117
 
118
  # --- Gradio Interface ---
119
  with gr.Blocks(title="CV & Job Matcher") as demo:
120
  gr.Markdown("# 🤖 CV & Job Description Matcher")
 
121
 
122
- with gr.Row():
123
- cv_input = gr.Textbox(label="CV", lines=15, value=EXAMPLE_CV)
124
- jd_input = gr.Textbox(label="Job Description", lines=15, value=EXAMPLE_JD)
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- analyze_btn = gr.Button("Analyze Match")
127
- output_display = gr.JSON(label="Match Output")
 
 
128
 
129
- # The api_name argument exposes this function as a named endpoint
 
130
  analyze_btn.click(
131
  fn=match_cv_jd,
132
  inputs=[cv_input, jd_input],
133
  outputs=output_display,
134
- api_name="/predict"
135
  )
136
 
137
  # --- Launch ---
138
  if __name__ == "__main__":
139
  load_model()
140
  # queue() is essential for processing concurrent requests on Spaces
141
- demo.queue()
 
142
  demo.launch(server_name="0.0.0.0")
 
18
  global model, tokenizer
19
  if model is not None:
20
  return
21
+
22
  print("Loading base model...")
23
+
24
  # Load base model
25
+ # Note: Using device_map="auto" is essential for large models
26
  base_model = AutoModelForCausalLM.from_pretrained(
27
  BASE_MODEL_ID,
28
  torch_dtype=torch.bfloat16,
29
  device_map="auto",
30
  token=HF_TOKEN
31
  )
32
+
33
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN)
34
  if tokenizer.pad_token is None:
35
  tokenizer.pad_token = tokenizer.eos_token
36
+
37
  print("Loading LoRA adapter...")
38
  peft_config = PeftConfig.from_pretrained(
39
  LORA_MODEL_ID,
40
  task_type="CAUSAL_LM",
41
  token=HF_TOKEN
42
  )
43
+
44
  model_with_lora = PeftModel.from_pretrained(
45
  base_model,
46
  LORA_MODEL_ID,
47
  config=peft_config,
48
  token=HF_TOKEN
49
  )
50
+
51
+ # Merge the LoRA adapter into the base model for a single, faster inference model
52
  model = model_with_lora.merge_and_unload()
53
  model.eval()
54
  print("Model fully loaded!")
55
 
56
  # --- Core Inference ---
57
+ @gr.to_gradio_output
58
  def match_cv_jd(cv_text: str, job_description: str) -> dict:
59
+ """
60
+ Performs the CV-JD matching using the merged Llama 3.1 model.
61
+ """
62
+ # Ensure model is loaded (important for environments where Gradio might reload)
63
  if model is None or tokenizer is None:
64
  load_model()
65
+
66
+ # System prompt guides the model's behavior and output format (JSON structure)
67
+ 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."""
68
+
69
+ # User prompt contains the input data
 
 
 
70
  user_prompt = f"""CV:
71
  ---
72
  {cv_text}
 
75
  ---
76
  {job_description}
77
  ---"""
78
+
79
  messages = [
80
  {"role": "system", "content": system_prompt},
81
  {"role": "user", "content": user_prompt}
82
  ]
83
+
84
+ # Prepare inputs for the model
85
  inputs = tokenizer.apply_chat_template(
86
  messages,
87
  add_generation_prompt=True,
88
  return_tensors="pt"
89
  ).to(model.device)
90
+
91
+ # Generate the response
92
  outputs = model.generate(
93
  inputs,
94
  max_new_tokens=1024,
95
+ temperature=0.01, # Keep temperature low for structured/deterministic output
96
  top_p=0.9,
97
  do_sample=True,
98
  eos_token_id=tokenizer.eos_token_id
99
  )
100
+
101
+ # Decode the response and clean up
102
  response_text = tokenizer.decode(
103
  outputs[0][inputs.shape[-1]:],
104
  skip_special_tokens=True
105
  ).strip()
106
+
107
+ # Attempt to parse the JSON output
108
  try:
109
+ # Robustly find the start and end of the JSON object in the response
110
  start = response_text.find("{")
111
  end = response_text.rfind("}")
112
  json_str = response_text[start:end+1]
113
+
114
  parsed = json.loads(json_str)
115
  return parsed
116
+ except Exception as e:
117
+ # Fallback for poorly formed output
118
+ print(f"JSON Parsing failed: {e}")
119
+ return {"raw": response_text, "error": "Failed to parse JSON output from model."}
120
 
121
  # --- Example Data ---
122
  EXAMPLE_CV = """**John Doe**
123
  Email: john.doe@example.com
124
+
125
  **Summary**
126
+ Experienced software engineer with 5 years in Python and backend development, specializing in building high-throughput microservices using FastAPI and Docker.
127
 
128
+ **Experience**
129
+ * Senior Software Engineer at TechCorp (2020-Present): Led migration of monolithic app to microservices, reducing latency by 40%.
130
+ """
131
  EXAMPLE_JD = """**Job Title: Senior Backend Engineer**
132
+ Responsibilities: Develop scalable, high-performance backend services using Python, ideally with experience in the FastAPI framework. Must have 4+ years of professional experience and familiarity with containerization (Docker/Kubernetes)."""
133
 
134
  # --- Gradio Interface ---
135
  with gr.Blocks(title="CV & Job Matcher") as demo:
136
  gr.Markdown("# 🤖 CV & Job Description Matcher")
137
+ 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.")
138
 
139
+ with gr.Row(variant="panel", equal_height=True):
140
+ cv_input = gr.Textbox(
141
+ label="1. Candidate CV/Resume (Text)",
142
+ lines=15,
143
+ value=EXAMPLE_CV,
144
+ interactive=True,
145
+ container=False
146
+ )
147
+ jd_input = gr.Textbox(
148
+ label="2. Job Description (JD) Text",
149
+ lines=15,
150
+ value=EXAMPLE_JD,
151
+ interactive=True,
152
+ container=False
153
+ )
154
 
155
+ analyze_btn = gr.Button("🚀 Analyze Match", variant="primary", scale=0)
156
+
157
+ # The output component for the structured JSON response
158
+ output_display = gr.JSON(label="3. Match Output (Structured JSON Response)", scale=1)
159
 
160
+ # *** THE FIX: The api_name argument is REMOVED for internal UI interactions. ***
161
+ # Gradio will automatically call the correct internal endpoint (/run/predict).
162
  analyze_btn.click(
163
  fn=match_cv_jd,
164
  inputs=[cv_input, jd_input],
165
  outputs=output_display,
166
+ # api_name="/predict" # <-- REMOVED THIS LINE
167
  )
168
 
169
  # --- Launch ---
170
  if __name__ == "__main__":
171
  load_model()
172
  # queue() is essential for processing concurrent requests on Spaces
173
+ demo.queue()
174
+ # Use 0.0.0.0 for hosting environments
175
  demo.launch(server_name="0.0.0.0")