{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Amazon Titan Models:\n",
    "\n",
    "[Titan Text: Optimized for natural language tasks like summarization, ranking, and text generation.](https://docs.aws.amazon.com/it_it/bedrock/latest/userguide/model-parameters-titan-text.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import boto3\n",
    "import yaml"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load credentials from YAML file\n",
    "with open(\"credentials.yml\", \"r\") as keyholder:\n",
    "    try:\n",
    "        credentials=yaml.safe_load(keyholder)\n",
    "    except yaml.YAMLError as exc:\n",
    "        print(exc)\n",
    "\n",
    "AWS_SERVER_PUBLIC_KEY=credentials['bedrock']['AWS_SERVER_PUBLIC_KEY']\n",
    "AWS_SERVER_SECRET_KEY=credentials['bedrock']['AWS_SERVER_SECRET_KEY']\n",
    "REGION_NAME=credentials['bedrock']['REGION_NAME']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_input_files():\n",
    "    # Load candidate resumes\n",
    "    with open(\"candidate_resumes.json\", \"r\") as candidates_file:\n",
    "        candidates = json.load(candidates_file)\n",
    "\n",
    "    # Load job description\n",
    "    with open(\"job_description.json\", \"r\") as job_desc_file:\n",
    "        job_description = json.load(job_desc_file)\n",
    "\n",
    "    return candidates, job_description"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the Bedrock client\n",
    "client = boto3.client(\n",
    "    \"bedrock-runtime\",\n",
    "    region_name=REGION_NAME,\n",
    "    aws_access_key_id=AWS_SERVER_PUBLIC_KEY,\n",
    "    aws_secret_access_key=AWS_SERVER_SECRET_KEY,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rank_candidates_with_titan(candidates, job_description):\n",
    "    job_desc_text = job_description[\"job_description\"]\n",
    "\n",
    "    prompt_template = (\n",
    "        \"You are an AI model skilled in evaluating resumes for job positions. \"\n",
    "        \"The job description is as follows:\\n{job_description}\\n\\n\"\n",
    "        \"Here are the candidate resumes:\\n\"\n",
    "        \"{candidate_resumes}\\n\\n\"\n",
    "        \"Please rank the candidates based on how well they match the job description, \"\n",
    "        \"providing a brief explanation for each ranking. Please explicitly give a number from 0 to 100 on how the candidate fits the position.\\n\"\n",
    "    )\n",
    "\n",
    "    # Prepare the candidates' details as text\n",
    "    candidate_texts = []\n",
    "    for candidate in candidates:\n",
    "        candidate_texts.append(\n",
    "            f\"Name: {candidate['name']}\\n\"\n",
    "            f\"Skills: {candidate['skills']}\\n\"\n",
    "            f\"Experience: {candidate['experience']}\\n\"\n",
    "            f\"Education: {candidate['education']}\\n\"\n",
    "        )\n",
    "    candidates_combined = \"\\n\\n\".join(candidate_texts)\n",
    "\n",
    "    # Construct the input text\n",
    "    input_text = prompt_template.format(\n",
    "        job_description=job_desc_text,\n",
    "        candidate_resumes=candidates_combined\n",
    "    )\n",
    "\n",
    "    try:\n",
    "        # Invoke Titan model\n",
    "        body = json.dumps({\"inputText\": input_text,\n",
    "                            \"textGenerationConfig\" : {\n",
    "                                \"maxTokenCount\": 1024, \n",
    "                                \"topP\":0.95, \n",
    "                                \"temperature\":0.2}})\n",
    "        modelId = \"amazon.titan-text-express-v1\" # \"amazon.titan-tg1-large\"\n",
    "        accept = \"application/json\"\n",
    "        contentType = \"application/json\"\n",
    "\n",
    "        response = client.invoke_model(\n",
    "            body=body, modelId=modelId, accept=accept, contentType=contentType\n",
    "        )\n",
    "        \n",
    "        \n",
    "        # Access token counts from response headers\n",
    "        input_tokens = response[\"ResponseMetadata\"][\"HTTPHeaders\"].get(\"x-amzn-bedrock-input-token-count\", \"Unknown\")\n",
    "        output_tokens = response[\"ResponseMetadata\"][\"HTTPHeaders\"].get(\"x-amzn-bedrock-output-token-count\", \"Unknown\")\n",
    "\n",
    "        print(f\"Input Tokens: {input_tokens}\")\n",
    "        print(f\"Output Tokens: {output_tokens}\")\n",
    "\n",
    "        # Debug: Print the raw response\n",
    "        print(\"Raw response received from the model:\")\n",
    "        print(response)\n",
    "\n",
    "        # Parse the model's response\n",
    "        response_body = response[\"body\"].read().decode('utf-8')\n",
    "        print(\"Decoded response body:\")\n",
    "        print(response_body)  # Debug the decoded response body\n",
    "        model_output = json.loads(response_body)\n",
    "\n",
    "        if \"results\" in model_output and len(model_output[\"results\"]) > 0:\n",
    "            return model_output[\"results\"][0][\"outputText\"]\n",
    "        else:\n",
    "            print(\"Error: Missing 'results' or 'outputText' in response.\")\n",
    "            return None\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Error while calling the model: {e}\")\n",
    "        return None\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input Tokens: 613\n",
      "Output Tokens: 624\n",
      "Raw response received from the model:\n",
      "{'ResponseMetadata': {'RequestId': '95a0fdc5-d6b2-4eb7-9a1c-175a6f8e2e8a', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Thu, 19 Dec 2024 11:02:05 GMT', 'content-type': 'application/json', 'content-length': '3173', 'connection': 'keep-alive', 'x-amzn-requestid': '95a0fdc5-d6b2-4eb7-9a1c-175a6f8e2e8a', 'x-amzn-bedrock-invocation-latency': '25207', 'x-amzn-bedrock-output-token-count': '624', 'x-amzn-bedrock-input-token-count': '613'}, 'RetryAttempts': 0}, 'contentType': 'application/json', 'body': <botocore.response.StreamingBody object at 0x11450cee0>}\n",
      "Decoded response body:\n",
      "{\"inputTextTokenCount\":613,\"results\":[{\"tokenCount\":624,\"outputText\":\"Ranking:\\n1. Alice Smith (90/100): Alice's resume matches the job description perfectly. She has 3 years of experience as a Python Developer, with a focus on web development and AWS services. She has developed web applications using Django and deployed them on AWS, which is exactly what the job requires. Additionally, her education in Computer Science provides a strong foundation for Python development.\\n2. Bob Johnson (80/100): Bob's resume also aligns well with the job description. While his experience is in Java Spring Framework, he has worked on scalable backend systems, which is relevant to the job. His education in Software Engineering further strengthens his qualifications.\\n3. Charlie Lee (75/100): Charlie's resume demonstrates experience in web development with Python and React, as well as integration with AWS DynamoDB. While his experience is not as deep as Alice's or Bob's, it still shows proficiency in the required technologies.\\n4. Diana Morales (70/100): Diana's resume showcases experience in cloud development with FastAPI and Azure Kubernetes Service, as well as data analysis with Python. While her experience is diverse, it may not be as directly relevant to the job as the other candidates.\\n5. Edward Turner (65/100): Edward's resume includes experience in backend development with Django and AWS EC2, as well as DevOps engineering with Terraform and AWS services. While his experience is strong, it may not be as focused on web development as the other candidates.\\n\\nExplanation:\\nAlice's resume stands out for its direct alignment with the job description. She has 3 years of experience as a Python Developer, with a focus on web development and AWS services. Her experience in developing web applications using Django and deploying them on AWS is exactly what the job requires. Additionally, her education in Computer Science provides a strong foundation for Python development.\\n\\nBob's resume also matches the job description well. While his experience is in Java Spring Framework, he has worked on scalable backend systems, which is relevant to the job. His education in Software Engineering further strengthens his qualifications.\\n\\nCharlie's resume demonstrates experience in web development with Python and React, as well as integration with AWS DynamoDB. While his experience is not as deep as Alice's or Bob's, it still shows proficiency in the required technologies.\\n\\nDiana's resume showcases experience in cloud development with FastAPI and Azure Kubernetes Service, as well as data analysis with Python. While her experience is diverse, it may not be as directly relevant to the job as the other candidates.\\n\\nEdward's resume includes experience in backend development with Django and AWS EC2, as well as DevOps engineering with Terraform and AWS services. While his experience is strong, it may not be as focused on web development as the other candidates.\\n\\nIt's important to note that the ranking is subjective and may vary depending on the specific requirements of the job and the preferences of the hiring team.\",\"completionReason\":\"FINISH\"}]}\n",
      "Ranking and feedback from Titan:\n",
      "Ranking:\n",
      "1. Alice Smith (90/100): Alice's resume matches the job description perfectly. She has 3 years of experience as a Python Developer, with a focus on web development and AWS services. She has developed web applications using Django and deployed them on AWS, which is exactly what the job requires. Additionally, her education in Computer Science provides a strong foundation for Python development.\n",
      "2. Bob Johnson (80/100): Bob's resume also aligns well with the job description. While his experience is in Java Spring Framework, he has worked on scalable backend systems, which is relevant to the job. His education in Software Engineering further strengthens his qualifications.\n",
      "3. Charlie Lee (75/100): Charlie's resume demonstrates experience in web development with Python and React, as well as integration with AWS DynamoDB. While his experience is not as deep as Alice's or Bob's, it still shows proficiency in the required technologies.\n",
      "4. Diana Morales (70/100): Diana's resume showcases experience in cloud development with FastAPI and Azure Kubernetes Service, as well as data analysis with Python. While her experience is diverse, it may not be as directly relevant to the job as the other candidates.\n",
      "5. Edward Turner (65/100): Edward's resume includes experience in backend development with Django and AWS EC2, as well as DevOps engineering with Terraform and AWS services. While his experience is strong, it may not be as focused on web development as the other candidates.\n",
      "\n",
      "Explanation:\n",
      "Alice's resume stands out for its direct alignment with the job description. She has 3 years of experience as a Python Developer, with a focus on web development and AWS services. Her experience in developing web applications using Django and deploying them on AWS is exactly what the job requires. Additionally, her education in Computer Science provides a strong foundation for Python development.\n",
      "\n",
      "Bob's resume also matches the job description well. While his experience is in Java Spring Framework, he has worked on scalable backend systems, which is relevant to the job. His education in Software Engineering further strengthens his qualifications.\n",
      "\n",
      "Charlie's resume demonstrates experience in web development with Python and React, as well as integration with AWS DynamoDB. While his experience is not as deep as Alice's or Bob's, it still shows proficiency in the required technologies.\n",
      "\n",
      "Diana's resume showcases experience in cloud development with FastAPI and Azure Kubernetes Service, as well as data analysis with Python. While her experience is diverse, it may not be as directly relevant to the job as the other candidates.\n",
      "\n",
      "Edward's resume includes experience in backend development with Django and AWS EC2, as well as DevOps engineering with Terraform and AWS services. While his experience is strong, it may not be as focused on web development as the other candidates.\n",
      "\n",
      "It's important to note that the ranking is subjective and may vary depending on the specific requirements of the job and the preferences of the hiring team.\n"
     ]
    }
   ],
   "source": [
    "if __name__ == \"__main__\":\n",
    "    candidates, job_description = read_input_files()\n",
    "    result = rank_candidates_with_titan(candidates, job_description)\n",
    "\n",
    "    if result:\n",
    "        print(\"Ranking and feedback from Titan:\")\n",
    "        print(result)\n",
    "    else:\n",
    "        print(\"Failed to get results from the model.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dinoVenv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
