mployd-engineering commited on
Commit
f13eeea
·
verified ·
1 Parent(s): e7ba396

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -38
app.py CHANGED
@@ -1,62 +1,90 @@
1
  import gradio as gr
2
  import torch
 
 
3
  import os
4
- # 🐛 FIX: Ensure both AutoTokenizer and AutoModel are imported from the transformers library.
5
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
 
7
- # 1. Define the Model ID
8
- MODEL_ID = "LlamaFactoryAI/cv-job-description-matching"
 
 
 
9
 
10
- # 2. Load the Model and Tokenizer
11
- # NOTE: If the model loading fails here, the application will crash with a clear error
12
- # in the logs, which is the correct behavior for a critical failure.
13
  try:
14
- print(f"Loading tokenizer and model for {MODEL_ID}...")
15
 
16
- # Use device_map="auto" to help handle memory if the model is large
17
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
18
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID, device_map="auto")
19
- print("Model loaded successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  except Exception as e:
22
- print(f"FATAL ERROR: Failed to load model {MODEL_ID}. Details: {e}")
23
- # Re-raise the exception to prevent the app from running broken
24
  raise
25
 
26
- # 3. Define the Prediction Function
27
  def match_cv_jd(cv_text: str, job_description_text: str):
28
  """
29
- Tokenizes the inputs, runs the model, and returns the prediction/score.
30
  """
31
  try:
32
- # Prepare the input for the matching task
33
- inputs = tokenizer(
34
- cv_text,
35
- job_description_text,
36
- return_tensors="pt",
37
- padding=True,
38
- truncation=True
39
- )
 
40
 
41
- # Get model output (logits)
42
- with torch.no_grad():
43
- outputs = model(**inputs)
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- # Process the output: Assuming it's a classification model
46
- probabilities = torch.softmax(outputs.logits, dim=1).tolist()[0]
47
 
48
- # The labels (e.g., match, no_match) are stored in the model's config
49
- predicted_index = torch.argmax(outputs.logits, dim=1).item()
50
- prediction = model.config.id2label[predicted_index]
51
- score = max(probabilities) * 100
 
 
52
 
53
- return f"Prediction: **{prediction}**\nConfidence Score: **{score:.2f}%**"
 
54
 
55
  except Exception as e:
56
- # Catch any errors that happen during the prediction phase (e.g., CUDA out of memory)
57
- return f"An error occurred during prediction: {e}. Please check the space logs."
58
 
59
- # 4. Create the Gradio Interface
60
  demo = gr.Interface(
61
  fn=match_cv_jd,
62
  inputs=[
@@ -65,7 +93,7 @@ demo = gr.Interface(
65
  ],
66
  outputs="markdown",
67
  title="LlamaFactory CV-Job Matching Demo",
68
- description=f"Interactive demo for the {MODEL_ID} model to assess CV/JD compatibility."
69
  )
70
 
71
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from peft import PeftModel
5
  import os
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 (found in the model card)
12
+ BASE_MODEL_ID = "akjindal53244/Llama-3.1-Storm-8B"
13
 
14
+ # --- Model Loading ---
 
 
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, # Recommended dtype for Llama models
22
+ device_map="auto" # Use accelerate to manage device placement
23
+ )
24
+
25
+ # 2. Load the base model's tokenizer
26
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
27
+
28
+ # 3. Load the LoRA adapter weights on top of the base model
29
+ model = PeftModel.from_pretrained(base_model, LORA_MODEL_ID)
30
+
31
+ # 4. Merge the LoRA weights into the base model (for faster inference)
32
+ model = model.merge_and_unload()
33
+ print("LoRA adapter merged and model ready successfully.")
34
 
35
  except Exception as e:
36
+ print(f"FATAL ERROR: Failed to load LoRA model. Details: {e}")
37
+ # Re-raise the exception to crash the space if loading fails
38
  raise
39
 
40
+ # 5. Define the Prediction/Matching Function
41
  def match_cv_jd(cv_text: str, job_description_text: str):
42
  """
43
+ Constructs the chat prompt, tokenizes, runs the LLM, and extracts the JSON output.
44
  """
45
  try:
46
+ # Define the exact prompt structure used for fine-tuning (from model card)
47
+ messages = [
48
+ {"role": "system", "content": """
49
+ You will receive a CV and a job description. Your task is to output a structured JSON format
50
+ that includes the following: 1. matching_analysis, 2. description, 3. score (0-100), 4. recommendation.
51
+ Your output must be in JSON format.
52
+ """},
53
+ {"role": "user", "content": f"<CV> {cv_text} </CV>\n<job_description> {job_description_text} </job_description>"},
54
+ ]
55
 
56
+ # Apply the chat template and generate tokens
57
+ inputs = tokenizer.apply_chat_template(
58
+ messages,
59
+ add_generation_prompt=True,
60
+ return_tensors="pt"
61
+ ).to(model.device) # Move to the correct device
62
+
63
+ # Generate the response
64
+ outputs = model.generate(
65
+ inputs,
66
+ max_new_tokens=512,
67
+ do_sample=False,
68
+ pad_token_id=tokenizer.eos_token_id # Important for generation
69
+ )
70
 
71
+ # Decode the generated text and clean up the prompt
72
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
73
 
74
+ # Extract the assistant's response (assuming the output starts after the user's prompt)
75
+ assistant_response_start = generated_text.rfind("assistant\n")
76
+ if assistant_response_start != -1:
77
+ raw_json_output = generated_text[assistant_response_start + len("assistant\n"):].strip()
78
+ else:
79
+ raw_json_output = generated_text
80
 
81
+ # For display, just return the raw text output
82
+ return f"### Model Output (JSON format expected):\n\n```json\n{raw_json_output}\n```"
83
 
84
  except Exception as e:
85
+ return f"An error occurred during prediction: {e}. If the model is too large, consider upgrading hardware."
 
86
 
87
+ # 6. Create the Gradio Interface
88
  demo = gr.Interface(
89
  fn=match_cv_jd,
90
  inputs=[
 
93
  ],
94
  outputs="markdown",
95
  title="LlamaFactory CV-Job Matching Demo",
96
+ description=f"Interactive demo for the {LORA_MODEL_ID} model (LoRA on {BASE_MODEL_ID})."
97
  )
98
 
99
  if __name__ == "__main__":