mployd-engineering commited on
Commit
709b6cb
·
verified ·
1 Parent(s): 3a51ea5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -206
app.py CHANGED
@@ -8,173 +8,111 @@ from fastapi import FastAPI
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from pydantic import BaseModel
10
 
11
-
12
  # --- Configuration ---
13
- # Base model: The instruction-tuned version of Llama 3.1 8B.
14
- BASE_MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
15
- # LoRA adapter: The CV/JD matching fine-tuned weights you requested.
16
- LORA_MODEL_ID = "LlamaFactoryAI/Llama-3.1-8B-Instruct-cv-job-description-matching"
17
 
18
- # Set the Hugging Face User Access Token here to authenticate and load gated models (like Llama 3.1).
19
- # You MUST replace the empty string with your actual token.
20
  HF_TOKEN = os.environ.get("HF_TOKEN")
21
 
22
- # --- Model and Tokenizer Initialization ---
23
- # Global variables to store the loaded components
24
  model = None
25
  tokenizer = None
26
 
27
  def load_model():
28
- """
29
- Loads the base model, tokenizer, and the LoRA adapter.
30
- Includes the critical fix for the 'Invalid task type' error by correctly
31
- loading and modifying the PeftConfig object, and adds authentication.
32
- """
33
  global model, tokenizer
34
-
35
  if model is not None:
36
- return # Model already loaded
 
 
 
 
 
 
 
 
37
 
38
- try:
39
- print(f"Loading base model: {BASE_MODEL_ID}...")
40
-
41
- # 1. Load the BASE model (Authentication via 'token' argument is added)
42
- # Using bfloat16 for efficiency and device_map="auto" for memory management
43
- base_model = AutoModelForCausalLM.from_pretrained(
44
- BASE_MODEL_ID,
45
- torch_dtype=torch.bfloat16,
46
- device_map="auto",
47
- token=HF_TOKEN # Pass the token for authentication
48
- )
49
-
50
- # 2. Load the base model's tokenizer (Authentication via 'token' argument is added)
51
- tokenizer = AutoTokenizer.from_pretrained(
52
- BASE_MODEL_ID,
53
- token=HF_TOKEN # Pass the token for authentication
54
- )
55
-
56
- # Set padding token for batch inference
57
- if tokenizer.pad_token is None:
58
- tokenizer.pad_token = tokenizer.eos_token
59
-
60
- # 3. Load and fix the PeftConfig (Authentication via 'token' argument is added)
61
- # CRITICAL FIX: The model's remote config file has an invalid 'text-generation'
62
- # task type. We must override it with the correct 'CAUSAL_LM' during loading
63
- # to prevent the ValueError.
64
- print("Loading and fixing PeftConfig with direct override...")
65
- peft_config = PeftConfig.from_pretrained(
66
- LORA_MODEL_ID,
67
- task_type="CAUSAL_LM", # <-- CRITICAL OVERRIDE
68
- token=HF_TOKEN # Pass the token for authentication
69
- )
70
-
71
- # 4. Load the LoRA adapter weights using the corrected config object (Authentication via 'token' argument is added)
72
- model = PeftModel.from_pretrained(
73
- base_model,
74
- LORA_MODEL_ID,
75
- config=peft_config,
76
- token=HF_TOKEN # Pass the token for authentication
77
- )
78
-
79
- # 5. Merge the LoRA weights into the base model for faster inference
80
- model = model.merge_and_unload()
81
- model.eval()
82
-
83
- print("LoRA adapter merged and model ready successfully.")
84
-
85
- except Exception as e:
86
- print(f"FATAL ERROR: Failed to load model or adapter. Details: {e}")
87
- # Re-raise the error to halt execution if loading failed
88
- raise
89
-
90
-
91
- # --- Core Inference Function ---
92
 
93
  def match_cv_jd(cv_text: str, job_description: str) -> str:
94
- """
95
- Generates a structured match analysis between a CV and a Job Description.
96
- """
97
- # Quick check for loaded model/tokenizer
98
  if model is None or tokenizer is None:
99
- return "Error: Model not loaded. Please check the logs."
100
 
101
- # 1. Define the system and user messages in the Llama 3 chat format
102
- # The system prompt instructs the model on its role and required output format.
103
  system_prompt = """
104
- 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:
105
- 1. matching_analysis: Analyze the CV against the job description to identify key strengths and gaps.
106
- 2. description: Summarize the relevance of the CV to the job description in a few concise sentences.
107
- 3. score: Provide a numerical compatibility score (0-100) based on qualifications, skills, and experience.
108
- 4. recommendation: Offer two concrete steps the candidate can take to improve their CV match for this specific job description.
109
-
110
- Your output MUST be a valid JSON object starting with '{' and ending with '}'. DO NOT include any text outside the JSON object.
111
  """
112
 
113
- # The user prompt combines the two inputs
114
  user_prompt = f"""
115
  CV:
116
  ---
117
  {cv_text}
118
  ---
119
-
120
  Job Description:
121
  ---
122
  {job_description}
123
  ---
124
-
125
- Generate the matching analysis as a JSON object:
126
  """
127
-
128
  messages = [
129
  {"role": "system", "content": system_prompt},
130
  {"role": "user", "content": user_prompt}
131
  ]
132
 
133
- # 2. Tokenize the input
134
  inputs = tokenizer.apply_chat_template(
135
- messages,
136
- add_generation_prompt=True,
137
  return_tensors="pt"
138
  ).to(model.device)
139
 
140
- # 3. Generate the response
141
- # We use aggressive generation parameters to encourage JSON output
142
  outputs = model.generate(
143
  inputs,
144
  max_new_tokens=1024,
145
- temperature=0.01, # Keep it low for deterministic JSON output
146
  top_p=0.9,
147
  do_sample=True,
148
  eos_token_id=tokenizer.eos_token_id
149
  )
150
-
151
- # 4. Decode and extract the JSON response
152
- response_text = tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True).strip()
153
-
154
- # Attempt to clean up and parse the JSON response
 
155
  try:
156
- # Sometimes the model adds extra text outside the JSON; find the first '{' and last '}'
157
- start_index = response_text.find('{')
158
- end_index = response_text.rfind('}')
159
- if start_index != -1 and end_index != -1 and end_index > start_index:
160
- json_str = response_text[start_index:end_index+1]
161
- analysis_dict = json.loads(json_str)
162
- # Format the JSON output nicely for the user interface
163
- return json.dumps(analysis_dict, indent=4)
164
- else:
165
- return f"Error: Model did not return valid JSON. Raw output:\n{response_text}"
166
-
167
- except json.JSONDecodeError as e:
168
- return f"JSON Decoding Error: {e}\nRaw Model Output:\n{response_text}"
169
- except Exception as e:
170
- return f"An unexpected error occurred during processing: {e}"
171
-
172
-
173
- # --- endpoint
174
 
175
  fastapi_app = FastAPI()
176
 
177
- # Allow cross-origin requests (optional but helpful)
178
  fastapi_app.add_middleware(
179
  CORSMiddleware,
180
  allow_origins=["*"],
@@ -182,111 +120,43 @@ fastapi_app.add_middleware(
182
  allow_headers=["*"],
183
  )
184
 
185
- # Request body schema
186
  class PredictRequest(BaseModel):
187
  cv: str
188
  jd: str
189
 
190
  @fastapi_app.post("/predict")
191
- def predict_api(payload: PredictRequest):
192
- # Ensure the model is loaded
193
  load_model()
194
  result = match_cv_jd(payload.cv, payload.jd)
195
-
196
- # Return already-formatted JSON string — parse it first
197
  try:
198
  return json.loads(result)
199
  except:
200
- return {"error": "Model returned non-JSON response", "raw": result}
201
-
202
 
203
- # --- Gradio Interface Setup ---
 
 
204
 
205
- # Example data for user convenience
206
- EXAMPLE_CV = """
207
- **John Doe**
208
- Email: john.doe@example.com | Phone: (555) 123-4567
209
 
210
- **Summary**
211
- 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.
212
-
213
- **Experience**
214
- * 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.
215
- * Software Developer, StartupX (2 years): Developed new features for a SaaS product using Python and PostgreSQL.
216
-
217
- **Skills**
218
- Python (Expert), Flask, SQL/PostgreSQL, Docker, Kubernetes, AWS (S3, EC2), Google Cloud, ETL, REST APIs, Agile methodologies.
219
- """
220
-
221
- EXAMPLE_JD = """
222
- **Job Title: Senior Backend Engineer**
223
-
224
- **Responsibilities:**
225
- - Develop and maintain scalable backend services using Python and Django.
226
- - Design, implement, and monitor data pipelines using modern ETL frameworks (e.g., Apache Airflow).
227
- - Collaborate with product managers to define feature specifications.
228
- - Mentor junior developers.
229
-
230
- **Required Qualifications:**
231
- - 5+ years of professional experience in backend software development.
232
- - Expert proficiency in Python and solid experience with a major web framework (Django or Flask).
233
- - Strong knowledge of SQL databases and optimization.
234
- - Experience with cloud platforms (AWS preferred) and containerization (Docker).
235
- - Prior experience leading technical projects or mentoring is a plus.
236
- """
237
-
238
- # Define the Gradio Interface
239
- with gr.Blocks(title="CV & Job Matcher (Mployd Alpha Version)") as demo:
240
- gr.Markdown(
241
- """
242
- # 🤖 CV & Job Description Matcher (Mployd Alpha version)
243
- Analyze a candidate's CV against a Job Description using Mployd Matching Model.
244
-
245
- The model provides a structured JSON analysis, including a compatibility score (0-100),
246
- a detailed analysis of strengths/gaps, and recommendations.
247
- """
248
- )
249
 
250
  with gr.Row():
251
- cv_input = gr.Textbox(
252
- label="Candidate CV/Resume Text",
253
- lines=20,
254
- value=EXAMPLE_CV,
255
- placeholder="Paste the candidate's CV text here..."
256
- )
257
-
258
- jd_input = gr.Textbox(
259
- label="Job Description Text",
260
- lines=20,
261
- value=EXAMPLE_JD,
262
- placeholder="Paste the Job Description text here..."
263
- )
264
-
265
- match_button = gr.Button("Analyze Match", variant="primary")
266
-
267
- output_display = gr.JSON(
268
- label="Match Analysis Output (JSON)",
269
- value={"status": "Click 'Analyze Match' to generate the report."}
270
- )
271
 
272
- # Example button to load the example inputs
273
- gr.Examples(
274
- examples=[[EXAMPLE_CV, EXAMPLE_JD]],
275
- inputs=[cv_input, jd_input],
276
- label="Load Example Data"
277
- )
278
 
279
- # Link the function to the button click event
280
- match_button.click(
281
- fn=match_cv_jd,
282
- inputs=[cv_input, jd_input],
283
- outputs=output_display
284
- )
285
 
 
 
286
 
287
- demo.app = fastapi_app
288
 
289
- # Launch the Gradio app
290
  if __name__ == "__main__":
291
- load_model() # Ensure model loading is called before demo launch
292
- demo.launch()
 
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from pydantic import BaseModel
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
 
 
 
15
  HF_TOKEN = os.environ.get("HF_TOKEN")
16
 
 
 
17
  model = None
18
  tokenizer = None
19
 
20
  def load_model():
 
 
 
 
 
21
  global model, tokenizer
 
22
  if model is not None:
23
+ return
24
+
25
+ print("Loading base model...")
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
+
35
+ if tokenizer.pad_token is None:
36
+ tokenizer.pad_token = tokenizer.eos_token
37
+
38
+ print("Loading LoRA adapter...")
39
+ peft_config = PeftConfig.from_pretrained(
40
+ LORA_MODEL_ID,
41
+ task_type="CAUSAL_LM",
42
+ token=HF_TOKEN
43
+ )
44
+
45
+ model_with_lora = PeftModel.from_pretrained(
46
+ base_model,
47
+ LORA_MODEL_ID,
48
+ config=peft_config,
49
+ token=HF_TOKEN
50
+ )
51
+
52
+ model = model_with_lora.merge_and_unload()
53
+ model.eval()
54
+ print("Model fully loaded!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  def match_cv_jd(cv_text: str, job_description: str) -> str:
 
 
 
 
57
  if model is None or tokenizer is None:
58
+ return "Model not loaded."
59
 
 
 
60
  system_prompt = """
61
+ You are a world-class CV and Job Description matching AI...
62
+ Your output MUST be valid JSON.
 
 
 
 
 
63
  """
64
 
 
65
  user_prompt = f"""
66
  CV:
67
  ---
68
  {cv_text}
69
  ---
 
70
  Job Description:
71
  ---
72
  {job_description}
73
  ---
 
 
74
  """
75
+
76
  messages = [
77
  {"role": "system", "content": system_prompt},
78
  {"role": "user", "content": user_prompt}
79
  ]
80
 
 
81
  inputs = tokenizer.apply_chat_template(
82
+ messages,
83
+ add_generation_prompt=True,
84
  return_tensors="pt"
85
  ).to(model.device)
86
 
 
 
87
  outputs = model.generate(
88
  inputs,
89
  max_new_tokens=1024,
90
+ temperature=0.01,
91
  top_p=0.9,
92
  do_sample=True,
93
  eos_token_id=tokenizer.eos_token_id
94
  )
95
+
96
+ response_text = tokenizer.decode(
97
+ outputs[0][inputs.shape[-1]:],
98
+ skip_special_tokens=True
99
+ ).strip()
100
+
101
  try:
102
+ start = response_text.find("{")
103
+ end = response_text.rfind("}")
104
+ json_str = response_text[start:end+1]
105
+ parsed = json.loads(json_str)
106
+ return json.dumps(parsed, indent=4)
107
+ except:
108
+ return response_text
109
+
110
+ # --------------------------------------------------------------------
111
+ # FASTAPI BACKEND
112
+ # --------------------------------------------------------------------
 
 
 
 
 
 
 
113
 
114
  fastapi_app = FastAPI()
115
 
 
116
  fastapi_app.add_middleware(
117
  CORSMiddleware,
118
  allow_origins=["*"],
 
120
  allow_headers=["*"],
121
  )
122
 
 
123
  class PredictRequest(BaseModel):
124
  cv: str
125
  jd: str
126
 
127
  @fastapi_app.post("/predict")
128
+ def predict_endpoint(payload: PredictRequest):
 
129
  load_model()
130
  result = match_cv_jd(payload.cv, payload.jd)
 
 
131
  try:
132
  return json.loads(result)
133
  except:
134
+ return {"raw": result}
 
135
 
136
+ # --------------------------------------------------------------------
137
+ # GRADIO UI
138
+ # --------------------------------------------------------------------
139
 
140
+ EXAMPLE_CV = "Example CV text..."
141
+ EXAMPLE_JD = "Example Job Description text..."
 
 
142
 
143
+ with gr.Blocks(title="CV & Job Matcher") as demo:
144
+ gr.Markdown("# CV & Job Description Matcher")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  with gr.Row():
147
+ cv_input = gr.Textbox(label="CV", lines=15, value=EXAMPLE_CV)
148
+ jd_input = gr.Textbox(label="Job Description", lines=15, value=EXAMPLE_JD)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ button = gr.Button("Analyze Match")
151
+ output = gr.JSON(label="Output")
 
 
 
 
152
 
153
+ button.click(match_cv_jd, inputs=[cv_input, jd_input], outputs=output)
 
 
 
 
 
154
 
155
+ # ⭐ This is the important part — mounts FastAPI + Gradio together ⭐
156
+ gr.mount_app(app=fastapi_app, blocks=demo, path="/")
157
 
158
+ # --------------------------------------------------------------------
159
 
 
160
  if __name__ == "__main__":
161
+ load_model()
162
+ demo.launch(server_name="0.0.0.0", server_port=7860)