mployd-engineering commited on
Commit
392cef7
·
verified ·
1 Parent(s): 4e61ddf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -94
app.py CHANGED
@@ -1,116 +1,251 @@
1
  import gradio as gr
2
  import torch
3
- import os
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
- from peft import PeftModel, PeftConfig # PeftConfig is essential for the fix
6
- from accelerate import Accelerator
7
 
8
- # --- Model Configuration ---
9
- # The LoRA adapter model on the Hugging Face Hub
10
- LORA_MODEL_ID = "LlamaFactoryAI/cv-job-description-matching"
11
- # The base model it was fine-tuned from (Llama-3.1-Storm-8B)
12
  BASE_MODEL_ID = "akjindal53244/Llama-3.1-Storm-8B"
 
 
 
13
 
14
- # --- Model Loading (CRITICAL SECTION: Contains the fix for the Invalid task type error) ---
15
- try:
16
- print(f"Loading base model: {BASE_MODEL_ID}...")
17
-
18
- # 1. Load the BASE model
19
- base_model = AutoModelForCausalLM.from_pretrained(
20
- BASE_MODEL_ID,
21
- torch_dtype=torch.bfloat16,
22
- device_map="auto" # Use accelerate to manage device placement (CPU/GPU)
23
- )
24
-
25
- # 2. Load the base model's tokenizer
26
- tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
27
-
28
- # 3. Load the LoRA configuration and override the invalid task_type
29
- peft_config = PeftConfig.from_pretrained(LORA_MODEL_ID)
30
-
31
- # 💥 CRITICAL FIX: Override the invalid 'text-generation' task type
32
- # for Causal Language Models (like Llama) to 'CAUSAL_LM'.
33
- peft_config.task_type = "CAUSAL_LM"
34
-
35
- # 4. Load the LoRA adapter weights using the corrected config
36
- model = PeftModel.from_pretrained(base_model, LORA_MODEL_ID, config=peft_config)
37
-
38
- # 5. Merge the LoRA weights into the base model for faster inference
39
- model = model.merge_and_unload()
40
-
41
- # Ensure the model is in evaluation mode
42
- model.eval()
43
-
44
- print("LoRA adapter merged and model ready successfully.")
45
-
46
- except Exception as e:
47
- print(f"FATAL ERROR: Failed to load LoRA model. Details: {e}")
48
- # Re-raise the exception to crash the space if loading fails
49
- raise
50
 
51
- # --- Prediction/Matching Function ---
52
- def match_cv_jd(cv_text: str, job_description_text: str):
53
  """
54
- Constructs the chat prompt, tokenizes, runs the LLM, and attempts to extract the JSON output.
 
55
  """
 
 
 
 
 
56
  try:
57
- # Define the exact prompt structure used for fine-tuning
58
- messages = [
59
- {"role": "system", "content": """
60
- You will receive a CV and a job description. Your task is to output a structured JSON format
61
- that includes the following: 1. matching_analysis, 2. description, 3. score (0-100), 4. recommendation.
62
- Your output must be in JSON format.
63
- """},
64
- {"role": "user", "content": f"<CV> {cv_text} </CV>\n<job_description> {job_description_text} </job_description>"},
65
- ]
66
 
67
- # Apply the chat template and generate tokens
68
- inputs = tokenizer.apply_chat_template(
69
- messages,
70
- add_generation_prompt=True,
71
- return_tensors="pt"
72
- ).to(model.device)
73
-
74
- # Generate the response
75
- outputs = model.generate(
76
- inputs,
77
- max_new_tokens=512,
78
- do_sample=False,
79
- pad_token_id=tokenizer.eos_token_id
80
  )
81
 
82
- # Decode the generated text and clean up the prompt
83
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=False)
84
 
85
- # Attempt to clean the output to show only the assistant's response
86
- assistant_response_start = generated_text.rfind("<|eot_id|>assistant\n")
 
87
 
88
- if assistant_response_start != -1:
89
- # Extract text starting after the assistant's role tag
90
- raw_json_output = generated_text[assistant_response_start + len("<|eot_id|>assistant\n"):].strip()
91
- else:
92
- # Fallback to the full generated text if the marker isn't found
93
- raw_json_output = generated_text
 
 
 
 
 
 
 
 
94
 
95
- # Remove any trailing tokens like <|eot_id|> for cleaner output
96
- raw_json_output = raw_json_output.replace("<|eot_id|>", "").strip()
 
97
 
98
- return f"### ✅ Matching Analysis Output (Expected JSON):\n\n```json\n{raw_json_output}\n```"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  except Exception as e:
101
- return f"### ❌ Prediction Error\n\nAn error occurred during prediction: {e}. This may indicate a hardware memory issue or a timeout."
102
-
103
- # --- Gradio Interface ---
104
- demo = gr.Interface(
105
- fn=match_cv_jd,
106
- inputs=[
107
- gr.Textbox(label="Paste CV Text", lines=10),
108
- gr.Textbox(label="Paste Job Description Text", lines=10)
109
- ],
110
- outputs="markdown",
111
- title="LlamaFactory CV-Job Matching Demo",
112
- description=f"Interactive demo for the {LORA_MODEL_ID} model (LoRA on {BASE_MODEL_ID}). This LLM expects a system prompt and outputs structured JSON."
113
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
 
115
  if __name__ == "__main__":
116
  demo.launch()
 
1
  import gradio as gr
2
  import torch
3
+ import json
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from peft import PeftModel
 
6
 
7
+ # --- Configuration ---
8
+ # Set the model IDs. Replace these with your actual model paths if different.
 
 
9
  BASE_MODEL_ID = "akjindal53244/Llama-3.1-Storm-8B"
10
+ LORA_MODEL_ID = "LlamaFactoryAI/cv-job-description-matching"
11
+ # Set API Key for external model calls. Leave empty for Canvas models.
12
+ API_KEY = ""
13
 
14
+ # --- Model and Tokenizer Initialization ---
15
+ # Global variables to store the loaded components
16
+ model = None
17
+ tokenizer = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ def load_model():
 
20
  """
21
+ Loads the base model, tokenizer, and the LoRA adapter.
22
+ Includes the critical fix for the 'Invalid task type' error.
23
  """
24
+ global model, tokenizer
25
+
26
+ if model is not None:
27
+ return # Model already loaded
28
+
29
  try:
30
+ print(f"Loading base model: {BASE_MODEL_ID}...")
 
 
 
 
 
 
 
 
31
 
32
+ # 1. Load the BASE model
33
+ # Using bfloat16 for efficiency and device_map="auto" for memory management
34
+ base_model = AutoModelForCausalLM.from_pretrained(
35
+ BASE_MODEL_ID,
36
+ torch_dtype=torch.bfloat16,
37
+ device_map="auto"
 
 
 
 
 
 
 
38
  )
39
 
40
+ # 2. Load the base model's tokenizer
41
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
42
 
43
+ # Set padding token for batch inference
44
+ if tokenizer.pad_token is None:
45
+ tokenizer.pad_token = tokenizer.eos_token
46
 
47
+ # 3. Define the override configuration dictionary
48
+ # CRITICAL FIX: The pre-trained LoRA adapter config sometimes incorrectly defaults
49
+ # to 'text-generation', which is disallowed by newer PEFT versions.
50
+ # We explicitly set it to 'CAUSAL_LM' (Causal Language Modeling) for Llama models.
51
+ peft_config_override = {
52
+ "task_type": "CAUSAL_LM"
53
+ }
54
+
55
+ # 4. Load the LoRA adapter weights using the corrected config
56
+ model = PeftModel.from_pretrained(
57
+ base_model,
58
+ LORA_MODEL_ID,
59
+ config=peft_config_override # Pass the dictionary to override the loaded config
60
+ )
61
 
62
+ # 5. Merge the LoRA weights into the base model for faster inference
63
+ model = model.merge_and_unload()
64
+ model.eval()
65
 
66
+ print("LoRA adapter merged and model ready successfully.")
67
+
68
+ except Exception as e:
69
+ print(f"FATAL ERROR: Failed to load model or adapter. Details: {e}")
70
+ raise
71
+
72
+ # Ensure the model is loaded when the script starts
73
+ load_model()
74
+
75
+
76
+ # --- Core Inference Function ---
77
+
78
+ def match_cv_jd(cv_text: str, job_description: str) -> str:
79
+ """
80
+ Generates a structured match analysis between a CV and a Job Description.
81
+
82
+ Args:
83
+ cv_text: The content of the candidate's CV.
84
+ job_description: The content of the job description.
85
+
86
+ Returns:
87
+ A formatted JSON string containing the matching analysis, score, and recommendation.
88
+ """
89
+ # Quick check for loaded model/tokenizer
90
+ if model is None or tokenizer is None:
91
+ return "Error: Model not loaded. Please check the logs."
92
+
93
+ # 1. Define the system and user messages in the Llama 3 chat format
94
+ # The system prompt instructs the model on its role and required output format.
95
+ system_prompt = """
96
+ You are a world-class CV and Job Description matching AI. You will receive a CV and a job description. Your task is to output a structured JSON format that includes the following:
97
+ 1. matching_analysis: Analyze the CV against the job description to identify key strengths and gaps.
98
+ 2. description: Summarize the relevance of the CV to the job description in a few concise sentences.
99
+ 3. score: Provide a numerical compatibility score (0-100) based on qualifications, skills, and experience.
100
+ 4. recommendation: Offer two concrete steps the candidate can take to improve their CV match for this specific job description.
101
+
102
+ Your output MUST be a valid JSON object starting with '{' and ending with '}'. DO NOT include any text outside the JSON object.
103
+ """
104
+
105
+ # The user prompt combines the two inputs
106
+ user_prompt = f"""
107
+ CV:
108
+ ---
109
+ {cv_text}
110
+ ---
111
+
112
+ Job Description:
113
+ ---
114
+ {job_description}
115
+ ---
116
+
117
+ Generate the matching analysis as a JSON object:
118
+ """
119
+
120
+ messages = [
121
+ {"role": "system", "content": system_prompt},
122
+ {"role": "user", "content": user_prompt}
123
+ ]
124
+
125
+ # 2. Tokenize the input
126
+ inputs = tokenizer.apply_chat_template(
127
+ messages,
128
+ add_generation_prompt=True,
129
+ return_tensors="pt"
130
+ ).to(model.device)
131
 
132
+ # 3. Generate the response
133
+ # We use aggressive generation parameters to encourage JSON output
134
+ outputs = model.generate(
135
+ inputs,
136
+ max_new_tokens=1024,
137
+ temperature=0.01, # Keep it low for deterministic JSON output
138
+ top_p=0.9,
139
+ do_sample=True,
140
+ eos_token_id=tokenizer.eos_token_id
141
+ )
142
+
143
+ # 4. Decode and extract the JSON response
144
+ response_text = tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True).strip()
145
+
146
+ # Attempt to clean up and parse the JSON response
147
+ try:
148
+ # Sometimes the model adds extra text outside the JSON; find the first '{' and last '}'
149
+ start_index = response_text.find('{')
150
+ end_index = response_text.rfind('}')
151
+ if start_index != -1 and end_index != -1 and end_index > start_index:
152
+ json_str = response_text[start_index:end_index+1]
153
+ analysis_dict = json.loads(json_str)
154
+ # Format the JSON output nicely for the user interface
155
+ return json.dumps(analysis_dict, indent=4)
156
+ else:
157
+ return f"Error: Model did not return valid JSON. Raw output:\n{response_text}"
158
+
159
+ except json.JSONDecodeError as e:
160
+ return f"JSON Decoding Error: {e}\nRaw Model Output:\n{response_text}"
161
  except Exception as e:
162
+ return f"An unexpected error occurred during processing: {e}"
163
+
164
+
165
+ # --- Gradio Interface Setup ---
166
+
167
+ # Example data for user convenience
168
+ EXAMPLE_CV = """
169
+ **John Doe**
170
+ Email: john.doe@example.com | Phone: (555) 123-4567
171
+
172
+ **Summary**
173
+ Highly motivated software engineer with 5 years of experience in Python, specialized in backend development and data processing pipelines using ETL tools and cloud services (AWS, Google Cloud). Proven ability to deliver scalable solutions.
174
+
175
+ **Experience**
176
+ * Senior Software Engineer, TechCorp (3 years): Led a team of 4 engineers. Designed and deployed microservices using Flask and Kubernetes. Achieved a 20% reduction in latency.
177
+ * Software Developer, StartupX (2 years): Developed new features for a SaaS product using Python and PostgreSQL.
178
+
179
+ **Skills**
180
+ Python (Expert), Flask, SQL/PostgreSQL, Docker, Kubernetes, AWS (S3, EC2), Google Cloud, ETL, REST APIs, Agile methodologies.
181
+ """
182
+
183
+ EXAMPLE_JD = """
184
+ **Job Title: Senior Backend Engineer**
185
+
186
+ **Responsibilities:**
187
+ - Develop and maintain scalable backend services using Python and Django.
188
+ - Design, implement, and monitor data pipelines using modern ETL frameworks (e.g., Apache Airflow).
189
+ - Collaborate with product managers to define feature specifications.
190
+ - Mentor junior developers.
191
+
192
+ **Required Qualifications:**
193
+ - 5+ years of professional experience in backend software development.
194
+ - Expert proficiency in Python and solid experience with a major web framework (Django or Flask).
195
+ - Strong knowledge of SQL databases and optimization.
196
+ - Experience with cloud platforms (AWS preferred) and containerization (Docker).
197
+ - Prior experience leading technical projects or mentoring is a plus.
198
+ """
199
+
200
+ # Define the Gradio Interface
201
+ with gr.Blocks(title="CV & Job Matcher (Llama 3 LoRA)") as demo:
202
+ gr.Markdown(
203
+ """
204
+ # 🤖 CV & Job Description Matcher (Llama 3.1 LoRA)
205
+ Analyze a candidate's CV against a Job Description using a Fine-Tuned Large Language Model.
206
+
207
+ The model provides a structured JSON analysis, including a compatibility score (0-100),
208
+ a detailed analysis of strengths/gaps, and recommendations.
209
+ """
210
+ )
211
+
212
+ with gr.Row():
213
+ cv_input = gr.Textbox(
214
+ label="Candidate CV/Resume Text",
215
+ lines=20,
216
+ value=EXAMPLE_CV,
217
+ placeholder="Paste the candidate's CV text here..."
218
+ )
219
+
220
+ jd_input = gr.Textbox(
221
+ label="Job Description Text",
222
+ lines=20,
223
+ value=EXAMPLE_JD,
224
+ placeholder="Paste the Job Description text here..."
225
+ )
226
+
227
+ match_button = gr.Button("Analyze Match", variant="primary")
228
+
229
+ output_display = gr.JSON(
230
+ label="Match Analysis Output (JSON)",
231
+ value={"status": "Click 'Analyze Match' to generate the report."},
232
+ lines=25
233
+ )
234
+
235
+ # Example button to load the example inputs
236
+ gr.Examples(
237
+ examples=[[EXAMPLE_CV, EXAMPLE_JD]],
238
+ inputs=[cv_input, jd_input],
239
+ label="Load Example Data"
240
+ )
241
+
242
+ # Link the function to the button click event
243
+ match_button.click(
244
+ fn=match_cv_jd,
245
+ inputs=[cv_input, jd_input],
246
+ outputs=output_display
247
+ )
248
 
249
+ # Launch the Gradio app
250
  if __name__ == "__main__":
251
  demo.launch()