{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Job description from google jobs" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# import pandas as pd\n", "# # from serpapi import GoogleSearch\n", "# import sqlite3\n", "# import datetime as dt\n", "# import http.client\n", "# import json\n", "# import config\n", "# import urllib.parse\n", "# import os\n", "# from sqlalchemy import create_engine\n", "# import psycopg2\n", "\n", "# def google_job_search(job_title, city_state):\n", "# '''\n", "# job_title(str): \"Data Scientist\", \"Data Analyst\"\n", "# city_state(str): \"Denver, CO\"\n", "# post_age,(str)(optional): \"3day\", \"week\", \"month\"\n", "# '''\n", "# query = f\"{job_title} {city_state}\"\n", "# params = {\n", "# \"engine\": \"google_jobs\",\n", "# \"q\": query,\n", "# \"hl\": \"en\",\n", "# \"api_key\": os.getenv('SerpAPIkey'),\n", "# # \"chips\": f\"date_posted:{post_age}\",\n", "# }\n", "\n", "# query_string = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)\n", "\n", "# conn = http.client.HTTPSConnection(\"serpapi.webscrapingapi.com/v1\")\n", "# try:\n", "# conn.request(\"GET\", f\"/v1?{query_string}\")\n", "# res = conn.getresponse()\n", "# try:\n", "# data = res.read()\n", "# finally:\n", "# res.close()\n", "# finally:\n", "# conn.close()\n", "\n", "# try:\n", "# json_data = json.loads(data.decode(\"utf-8\"))\n", "# jobs_results = json_data['google_jobs_results']\n", "# job_columns = ['title', 'company_name', 'location', 'description']\n", "# df = pd.DataFrame(jobs_results, columns=job_columns)\n", "# return df\n", "# except (KeyError, json.JSONDecodeError) as e:\n", "# print(f\"Error occurred for search: {job_title} in {city_state}\")\n", "# print(f\"Error message: {str(e)}\")\n", "# return None\n", "\n", "# def sql_dump(df, table):\n", "# engine = create_engine(f\"postgresql://{os.getenv('MasterName')}:{os.getenv('MasterPass')}@{os.getenv('RDS_EndPoint')}:5432/postgres\")\n", "# with engine.connect() as conn:\n", "# df.to_sql(table, conn, if_exists='append', chunksize=1000, method='multi', index=False)\n", "\n", "# def main(job_list, city_state_list):\n", "# for job in job_list:\n", "# for city_state in city_state_list:\n", "# df_10jobs = google_job_search(job, city_state)\n", "# if df_10jobs is not None:\n", "# print(f'City: {city_state} Job: {job}')\n", "# print(df_10jobs.shape)\n", "# date = dt.datetime.today().strftime('%Y-%m-%d')\n", "# df_10jobs['retrieve_date'] = date\n", "# sql_dump(df_10jobs, 'datajobs24')\n", "\n", "# return None" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import sqlite3\n", "import datetime as dt\n", "import http.client\n", "import json\n", "import urllib.parse\n", "import os\n", "from sqlalchemy import create_engine\n", "from concurrent.futures import ThreadPoolExecutor, as_completed\n", "from dotenv import load_dotenv\n", "\n", "load_dotenv()\n", "\n", "def google_job_search(job_title, city_state, start=0):\n", " '''\n", " job_title(str): \"Data Scientist\", \"Data Analyst\"\n", " city_state(str): \"Denver, CO\"\n", " post_age,(str)(optional): \"3day\", \"week\", \"month\"\n", " '''\n", " query = f\"{job_title} {city_state}\"\n", " params = {\n", " \"api_key\": os.getenv('SerpAPIkey'),\n", " \"engine\": \"google_jobs\",\n", " \"q\": query,\n", " \"hl\": \"en\",\n", " \"start\": start,\n", " # \"chips\": f\"date_posted:{post_age}\",\n", " }\n", "\n", " query_string = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)\n", "\n", " conn = http.client.HTTPSConnection(\"serpapi.webscrapingapi.com\")\n", " try:\n", " conn.request(\"GET\", f\"/v1?{query_string}\")\n", " res = conn.getresponse()\n", " try:\n", " data = res.read()\n", " finally:\n", " res.close()\n", " finally:\n", " conn.close()\n", "\n", " try:\n", " json_data = json.loads(data.decode(\"utf-8\"))\n", " jobs_results = json_data['google_jobs_results']\n", " job_columns = ['title', 'company_name', 'location', 'description', 'extensions', 'job_id']\n", " df = pd.DataFrame(jobs_results, columns=job_columns)\n", " return df\n", " except (KeyError, json.JSONDecodeError) as e:\n", " print(f\"Error occurred for search: {job_title} in {city_state}\")\n", " print(f\"Error message: {str(e)}\")\n", " return None\n", "\n", "def sql_dump(df, table):\n", " engine = create_engine(f\"postgresql://{os.getenv('PSQL_MASTER_NAME')}:{os.getenv('PSQL_KEY')}@{os.getenv('RDS_ENDPOINT')}:5432/postgres\")\n", " with engine.connect() as conn:\n", " df.to_sql(table, conn, if_exists='append', chunksize=20, method='multi', index=False)\n", " print(f\"Dumped {df.shape} to SQL table {table}\")\n", "\n", "def process_batch(job, city_state, start):\n", " df_10jobs = google_job_search(job, city_state, start)\n", " if df_10jobs is not None:\n", " print(f'City: {city_state} Job: {job} Start: {start}')\n", " print(df_10jobs.shape)\n", " date = dt.datetime.today().strftime('%Y-%m-%d')\n", " df_10jobs['retrieve_date'] = date\n", " df_10jobs.drop_duplicates(subset=['job_id', 'company_name'], inplace=True)\n", " rows_affected = sql_dump(df_10jobs, 'usajobs24')\n", " print(f\"Rows affected: {rows_affected}\")\n", "\n", "def main(job_list, city_state_list):\n", " with ThreadPoolExecutor() as executor:\n", " futures = []\n", " for job in job_list:\n", " for city_state in city_state_list:\n", " for start in range(0, 2):\n", " future = executor.submit(process_batch, job, city_state, start)\n", " futures.append(future)\n", "\n", " for future in as_completed(futures):\n", " future.result()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "# job_list = [\"Data Analyst\", \"Data Engineer\", \"Big Data Engineer\"]\n", "# simple_city_state_list = [\"Menlo Park CA\", \"Palo Alto CA\", \"San Francisco CA\", \"Mountain View CA\"]\n", "# main(job_list, simple_city_state_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Great now that we have written some data lets read it." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "from sqlalchemy import create_engine\n", "\n", "def read_data_from_db(table_name):\n", " engine = create_engine(f\"postgresql://{os.getenv('PSQL_MASTER_NAME')}:{os.getenv('PSQL_KEY')}@{os.getenv('RDS_ENDPOINT')}:5432/postgres\")\n", " \n", " try:\n", " with engine.connect() as conn:\n", " query = f'SELECT * FROM \"{table_name}\"'\n", " df = pd.read_sql(query, conn)\n", " return df\n", " except Exception as e:\n", " print(f\"Error occurred while reading data from the database: {str(e)}\")\n", " return None\n", "\n", "data24_df = read_data_from_db('usajobstest')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(417, 7)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data24_df.shape" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
titlecompany_namelocationdescriptionextensionsjob_idretrieve_date
0Business Intelligence AnalystNuvolumSan Francisco, CANuvolum combines innovative, data-driven strat...{\"3 days ago\",Full-time,\"No degree mentioned\"}eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2...2024-05-04
1Sr. Strategy and Business Intelligence AnalystSunrunSan Francisco, CA (+1 other)Everything we do at Sunrun is driven by a dete...{\"12 days ago\",Full-time,\"Health insurance\",\"D...eyJqb2JfdGl0bGUiOiJTci4gU3RyYXRlZ3kgYW5kIEJ1c2...2024-05-04
2Business Intelligence AnalystSideAnywhereSide, Inc. seeks Business Intelligence Analyst...{\"11 days ago\",\"151,736–157,000 a year\",\"Work ...eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2...2024-05-04
3Senior Business Intelligence DeveloperTekNavigators StaffingSan Francisco, CARole: Senior BI Developer\\n\\nLocation: San Fra...{\"20 hours ago\",Contractor,\"No degree mentioned\"}eyJqb2JfdGl0bGUiOiJTZW5pb3IgQnVzaW5lc3MgSW50ZW...2024-05-04
4Senior Business Intelligence AnalystFIS Fidelity National Information ServicesSan Francisco, CAPosition Type : Full time Type Of Hire : Exper...{\"19 days ago\",Full-time}eyJqb2JfdGl0bGUiOiJTZW5pb3IgQnVzaW5lc3MgSW50ZW...2024-05-04
........................
412Business Intelligence Analyst - Diabetes Marke...MedtronicAnywhereCareers that Change Lives\\n\\nWe are looking fo...{\"10 days ago\",\"Work from home\",Full-time,\"No ...eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2...2024-05-04
413IT Analyst, Business Intelligence/Data Warehou...Keck Medicine of USCAlhambra, CAActively design and develop ETL solutions that...{\"13 days ago\",Full-time}eyJqb2JfdGl0bGUiOiJJVCBBbmFseXN0LCBCdXNpbmVzcy...2024-05-04
414Director, Business IntelligenceDeutsch LALos Angeles, CADIRECTOR, BUSINESS INTELLIGENCE\\n\\nWe are seek...{\"3 days ago\",Full-time,\"No degree mentioned\"}eyJqb2JfdGl0bGUiOiJEaXJlY3RvciwgQnVzaW5lc3MgSW...2024-05-04
415Business Intelligence Programmer 1U.S. BankLos Angeles, CAAt U.S. Bank, we’re on a journey to do our bes...{\"3 days ago\",Full-time,\"Health insurance\",\"De...eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2...2024-05-04
416Business Intelligence AnalystBIGOLos Angeles, CALocation: 10250 Constellation Blvd., Century C...{\"1 day ago\",Full-time,\"Health insurance\",\"Den...eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2...2024-05-04
\n", "

417 rows × 7 columns

\n", "
" ], "text/plain": [ " title \\\n", "0 Business Intelligence Analyst \n", "1 Sr. Strategy and Business Intelligence Analyst \n", "2 Business Intelligence Analyst \n", "3 Senior Business Intelligence Developer \n", "4 Senior Business Intelligence Analyst \n", ".. ... \n", "412 Business Intelligence Analyst - Diabetes Marke... \n", "413 IT Analyst, Business Intelligence/Data Warehou... \n", "414 Director, Business Intelligence \n", "415 Business Intelligence Programmer 1 \n", "416 Business Intelligence Analyst \n", "\n", " company_name location \\\n", "0 Nuvolum San Francisco, CA \n", "1 Sunrun San Francisco, CA (+1 other) \n", "2 Side Anywhere \n", "3 TekNavigators Staffing San Francisco, CA \n", "4 FIS Fidelity National Information Services San Francisco, CA \n", ".. ... ... \n", "412 Medtronic Anywhere \n", "413 Keck Medicine of USC Alhambra, CA \n", "414 Deutsch LA Los Angeles, CA \n", "415 U.S. Bank Los Angeles, CA \n", "416 BIGO Los Angeles, CA \n", "\n", " description \\\n", "0 Nuvolum combines innovative, data-driven strat... \n", "1 Everything we do at Sunrun is driven by a dete... \n", "2 Side, Inc. seeks Business Intelligence Analyst... \n", "3 Role: Senior BI Developer\\n\\nLocation: San Fra... \n", "4 Position Type : Full time Type Of Hire : Exper... \n", ".. ... \n", "412 Careers that Change Lives\\n\\nWe are looking fo... \n", "413 Actively design and develop ETL solutions that... \n", "414 DIRECTOR, BUSINESS INTELLIGENCE\\n\\nWe are seek... \n", "415 At U.S. Bank, we’re on a journey to do our bes... \n", "416 Location: 10250 Constellation Blvd., Century C... \n", "\n", " extensions \\\n", "0 {\"3 days ago\",Full-time,\"No degree mentioned\"} \n", "1 {\"12 days ago\",Full-time,\"Health insurance\",\"D... \n", "2 {\"11 days ago\",\"151,736–157,000 a year\",\"Work ... \n", "3 {\"20 hours ago\",Contractor,\"No degree mentioned\"} \n", "4 {\"19 days ago\",Full-time} \n", ".. ... \n", "412 {\"10 days ago\",\"Work from home\",Full-time,\"No ... \n", "413 {\"13 days ago\",Full-time} \n", "414 {\"3 days ago\",Full-time,\"No degree mentioned\"} \n", "415 {\"3 days ago\",Full-time,\"Health insurance\",\"De... \n", "416 {\"1 day ago\",Full-time,\"Health insurance\",\"Den... \n", "\n", " job_id retrieve_date \n", "0 eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2... 2024-05-04 \n", "1 eyJqb2JfdGl0bGUiOiJTci4gU3RyYXRlZ3kgYW5kIEJ1c2... 2024-05-04 \n", "2 eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2... 2024-05-04 \n", "3 eyJqb2JfdGl0bGUiOiJTZW5pb3IgQnVzaW5lc3MgSW50ZW... 2024-05-04 \n", "4 eyJqb2JfdGl0bGUiOiJTZW5pb3IgQnVzaW5lc3MgSW50ZW... 2024-05-04 \n", ".. ... ... \n", "412 eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2... 2024-05-04 \n", "413 eyJqb2JfdGl0bGUiOiJJVCBBbmFseXN0LCBCdXNpbmVzcy... 2024-05-04 \n", "414 eyJqb2JfdGl0bGUiOiJEaXJlY3RvciwgQnVzaW5lc3MgSW... 2024-05-04 \n", "415 eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2... 2024-05-04 \n", "416 eyJqb2JfdGl0bGUiOiJCdXNpbmVzcyBJbnRlbGxpZ2VuY2... 2024-05-04 \n", "\n", "[417 rows x 7 columns]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data24_df" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# get the list of unique title, company_name pairs\n", "title_company = data24_df[['title', 'company_name', 'location', 'description']].drop_duplicates()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
titlecompany_namelocationdescription
0Business Intelligence AnalystNuvolumSan Francisco, CANuvolum combines innovative, data-driven strat...
1Sr. Strategy and Business Intelligence AnalystSunrunSan Francisco, CA (+1 other)Everything we do at Sunrun is driven by a dete...
2Business Intelligence AnalystSideAnywhereSide, Inc. seeks Business Intelligence Analyst...
3Senior Business Intelligence DeveloperTekNavigators StaffingSan Francisco, CARole: Senior BI Developer\\n\\nLocation: San Fra...
4Senior Business Intelligence AnalystFIS Fidelity National Information ServicesSan Francisco, CAPosition Type : Full time Type Of Hire : Exper...
...............
412Business Intelligence Analyst - Diabetes Marke...MedtronicAnywhereCareers that Change Lives\\n\\nWe are looking fo...
413IT Analyst, Business Intelligence/Data Warehou...Keck Medicine of USCAlhambra, CAActively design and develop ETL solutions that...
414Director, Business IntelligenceDeutsch LALos Angeles, CADIRECTOR, BUSINESS INTELLIGENCE\\n\\nWe are seek...
415Business Intelligence Programmer 1U.S. BankLos Angeles, CAAt U.S. Bank, we’re on a journey to do our bes...
416Business Intelligence AnalystBIGOLos Angeles, CALocation: 10250 Constellation Blvd., Century C...
\n", "

405 rows × 4 columns

\n", "
" ], "text/plain": [ " title \\\n", "0 Business Intelligence Analyst \n", "1 Sr. Strategy and Business Intelligence Analyst \n", "2 Business Intelligence Analyst \n", "3 Senior Business Intelligence Developer \n", "4 Senior Business Intelligence Analyst \n", ".. ... \n", "412 Business Intelligence Analyst - Diabetes Marke... \n", "413 IT Analyst, Business Intelligence/Data Warehou... \n", "414 Director, Business Intelligence \n", "415 Business Intelligence Programmer 1 \n", "416 Business Intelligence Analyst \n", "\n", " company_name location \\\n", "0 Nuvolum San Francisco, CA \n", "1 Sunrun San Francisco, CA (+1 other) \n", "2 Side Anywhere \n", "3 TekNavigators Staffing San Francisco, CA \n", "4 FIS Fidelity National Information Services San Francisco, CA \n", ".. ... ... \n", "412 Medtronic Anywhere \n", "413 Keck Medicine of USC Alhambra, CA \n", "414 Deutsch LA Los Angeles, CA \n", "415 U.S. Bank Los Angeles, CA \n", "416 BIGO Los Angeles, CA \n", "\n", " description \n", "0 Nuvolum combines innovative, data-driven strat... \n", "1 Everything we do at Sunrun is driven by a dete... \n", "2 Side, Inc. seeks Business Intelligence Analyst... \n", "3 Role: Senior BI Developer\\n\\nLocation: San Fra... \n", "4 Position Type : Full time Type Of Hire : Exper... \n", ".. ... \n", "412 Careers that Change Lives\\n\\nWe are looking fo... \n", "413 Actively design and develop ETL solutions that... \n", "414 DIRECTOR, BUSINESS INTELLIGENCE\\n\\nWe are seek... \n", "415 At U.S. Bank, we’re on a journey to do our bes... \n", "416 Location: 10250 Constellation Blvd., Century C... \n", "\n", "[405 rows x 4 columns]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "title_company" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "data24_df.to_csv('data24.csv', index=False)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "# from typing import List, Optional\n", "# from langchain_core.pydantic_v1 import BaseModel, Field\n", "\n", "# class CompanyOverview(BaseModel):\n", "# \"\"\"\n", "# A model for capturing key information about the company offering the job.\n", " \n", "# Extract relevant details about the company from the job description, \n", "# including a brief overview of its industry and products, its mission and \n", "# values, size, and location(s).\n", " \n", "# Focus on capturing the most salient points that give a well-rounded picture\n", "# of the company and its culture.\n", "# \"\"\"\n", "\n", "# about: Optional[str] = Field(\n", "# None, \n", "# description=\"\"\"Brief description of the company, its industry, products, services, \n", "# and any notable achievements or differentiators\"\"\"\n", "# )\n", "\n", "# mission_and_values: Optional[str] = Field(\n", "# None,\n", "# description=\"\"\"Company mission, vision, values, and culture, including commitments \n", "# to diversity, inclusion, social responsibility, and work-life balance\"\"\"\n", "# )\n", " \n", "# size: Optional[str] = Field(\n", "# None,\n", "# description=\"Details about company size, such as number of employees\")\n", " \n", "# locations: Optional[str] = Field(\n", "# None,\n", "# description=\"\"\"Geographic presence of the company, including headquarters, \n", "# offices, and any remote work options\"\"\"\n", "# )\n", " \n", "# city: Optional[str] = Field(None, description=\"City where the company is located\")\n", " \n", "# state: Optional[str] = Field(None, description=\"State where the company is located\")\n", "\n", "\n", "# class RoleSummary(BaseModel):\n", "# \"\"\"\n", "# A model for capturing the key summary points about the job role.\n", " \n", "# Extract the essential high-level details about the role from the job description,\n", "# such as the job title, the team or department the role belongs to, the role type, \n", "# and any remote work options.\n", " \n", "# Prioritize information that helps understand the overall scope and positioning \n", "# of the role within the company.\n", "# \"\"\"\n", " \n", "# title: str = Field(..., description=\"Title of the job role\")\n", " \n", "# team_or_department: Optional[str] = Field(\n", "# None,\n", "# description=\"\"\"Team, department, or business unit the role belongs to, \n", "# including any collaborations with other teams\"\"\"\n", "# )\n", " \n", "# role_type: Optional[str] = Field(\n", "# None,\n", "# description=\"Type of role (full-time, part-time, contract, etc.)\"\n", "# )\n", " \n", "# remote: Optional[str] = Field(\n", "# None,\n", "# description=\"Remote work options for the role (full, hybrid, none)\"\n", "# )\n", "\n", "# class ResponsibilitiesAndQualifications(BaseModel):\n", "# \"\"\"\n", "# A model for capturing the key responsibilities, requirements, and preferred \n", "# qualifications for the job role.\n", "\n", "# Extract the essential duties and expectations of the role, the mandatory \n", "# educational background and experience required, and any additional skills \n", "# or characteristics that are desirable but not strictly necessary.\n", "\n", "# The goal is to provide a clear and comprehensive picture of what the role \n", "# entails and what qualifications the ideal candidate should possess.\n", "# \"\"\"\n", "\n", "# responsibilities: List[str] = Field(\n", "# description=\"\"\"The core duties, tasks, and expectations of the role, encompassing \n", "# areas such as metrics, theories, business understanding, product \n", "# direction, systems, leadership, decision making, strategy, and \n", "# collaboration, as described in the job description\"\"\"\n", "# )\n", "\n", "# required_qualifications: List[str] = Field(\n", "# description=\"\"\"The essential educational qualifications (e.g., Doctorate, \n", "# Master's, Bachelor's degrees in specific fields) and years of \n", "# relevant professional experience that are mandatory for the role, \n", "# including any alternative acceptable combinations of education \n", "# and experience, as specified in the job description\"\"\"\n", "# )\n", " \n", "# preferred_qualifications: List[str] = Field(\n", "# description=\"\"\"Any additional skills, experiences, characteristics, or domain \n", "# expertise that are valuable for the role but not absolute \n", "# requirements, such as proficiency with specific tools/technologies, \n", "# relevant soft skills, problem solving abilities, and industry \n", "# knowledge, as mentioned in the job description as preferred or \n", "# nice-to-have qualifications\"\"\"\n", "# )\n", " \n", "# class CompensationAndBenefits(BaseModel):\n", "# \"\"\"\n", "# A model for capturing the compensation and benefits package for the job role.\n", " \n", "# Extract details about the salary or pay range, bonus and equity compensation, \n", "# benefits, and perks from the job description.\n", " \n", "# Aim to provide a comprehensive view of the total rewards offered for the role,\n", "# including both monetary compensation and non-monetary benefits and perks.\n", "# \"\"\"\n", " \n", "# salary_or_pay_range: Optional[str] = Field(\n", "# None,\n", "# description=\"\"\"The salary range or hourly pay range for the role, including \n", "# any specific numbers or bands mentioned in the job description\"\"\"\n", "# )\n", " \n", "# bonus_and_equity: Optional[str] = Field(\n", "# None,\n", "# description=\"\"\"Any information about bonus compensation, such as signing bonuses, \n", "# annual performance bonuses, or other incentives, as well as details \n", "# about equity compensation like stock options or RSUs\"\"\"\n", "# )\n", " \n", "# benefits: Optional[List[str]] = Field(\n", "# None,\n", "# description=\"\"\"A list of benefits offered for the role, such as health insurance, \n", "# dental and vision coverage, retirement plans (401k, pension), paid \n", "# time off (vacation, sick days, holidays), parental leave, and any \n", "# other standard benefits mentioned in the job description\"\"\"\n", "# )\n", " \n", "# perks: Optional[List[str]] = Field(\n", "# None,\n", "# description=\"\"\"A list of additional perks and amenities offered, such as free food \n", "# or snacks, commuter benefits, wellness programs, learning and development \n", "# stipends, employee discounts, or any other unique perks the company \n", "# provides to its employees, as mentioned in the job description\"\"\"\n", "# )\n", "\n", "# class JobDescription(BaseModel):\n", "# \"\"\"Extracted information from a job description.\"\"\"\n", "# company_overview: CompanyOverview\n", "# role_summary: RoleSummary\n", "# responsibilities_and_qualifications: ResponsibilitiesAndQualifications\n", "# compensation_and_benefits: CompensationAndBenefits" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "sys.path.append('../utils')\n", "\n", "from job_desc_pydantic import JobDescription" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from typing import List, Optional\n", "\n", "from langchain.chains import create_structured_output_runnable\n", "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n", "from langchain_core.pydantic_v1 import BaseModel, Field\n", "\n", "from langchain_groq import ChatGroq\n", "from dotenv import load_dotenv\n", "import os\n", "\n", "load_dotenv()" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\n", " \"system\",\n", " \"\"\"You are an expert at identifying key aspects of job descriptions. Your task is to extract important information from a raw job description and organize it into a structured format using the ResponsibilitiesAndQualifications class.\n", "\n", " When parsing the job description, your goal is to capture as much relevant information as possible in the appropriate fields of the class. This includes:\n", "\n", " 1. All key responsibilities and duties of the role, covering the full range of tasks and expectations.\n", " 2. The required educational qualifications and years of experience, including different acceptable combinations.\n", " 3. Any additional preferred skills, experiences, and characteristics that are desirable for the role.\n", "\n", " Avoid summarizing or paraphrasing the information. Instead, extract the details as closely as possible to how they appear in the original job description. The aim is to organize and structure the raw data, not to condense or interpret it.\n", "\n", " Some specific things to look out for:\n", " - Responsibilities related to metrics, theories, business understanding, product direction, systems, leadership, decision making, strategy, and collaboration\n", " - Required degrees (Doctorate, Master's, Bachelor's) in relevant fields, along with the corresponding years of experience\n", " - Preferred qualifications like years of coding experience, soft skills, problem solving abilities, and domain expertise\n", "\n", " If any of these details are missing from the job description, simply omit them from the output rather than trying to infer or fill in the gaps.\n", "\n", " The structured data you extract will be used for further analysis and insights downstream, so err on the side of including more information rather than less. The key is to make the unstructured job description data more organized and manageable while still retaining all the important details.\n", " \"\"\",\n", " ),\n", " (\"human\", \"{text}\"),\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/leowalker/anaconda3/envs/datajobs/lib/python3.11/site-packages/langchain_core/_api/beta_decorator.py:87: LangChainBetaWarning: The method `ChatGroq.with_structured_output` is in beta. It is actively being worked on, so the API may change.\n", " warn_beta(\n" ] } ], "source": [ "llm = ChatGroq(model_name=\"llama3-70b-8192\")\n", "\n", "extractor = prompt | llm.with_structured_output(\n", " schema=JobDescription,\n", " method=\"function_calling\",\n", " include_raw=False,\n", ")" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "test_description = title_company['description'][2]" ] }, { "cell_type": "code", "execution_count": 157, "metadata": {}, "outputs": [], "source": [ "jobdesc = extractor.invoke(test_description)" ] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"company_overview\": {\n", " \"about\": \"Microsoft is a leading technology company responsible for delivering the quality experience to over 500M+ monthly active users around the world in Microsoft\\u2019s search engine, Bing.\",\n", " \"mission_and_values\": \"Empower every person and every organization on the planet to achieve more.\",\n", " \"size\": \"500M+ users\",\n", " \"locations\": \"Global\",\n", " \"city\": \"Redmond\",\n", " \"state\": null\n", " },\n", " \"role_summary\": {\n", " \"title\": \"Principal Data Scientist\",\n", " \"team_or_department\": \"Search + Distribution (S+D) team\",\n", " \"role_type\": \"Full-time\",\n", " \"remote\": \"N/A\"\n", " },\n", " \"responsibilities_and_qualifications\": {\n", " \"responsibilities\": [\n", " \"Define, invent, and deliver online and offline behavioral and human labeled metrics which accurately measure the satisfaction and success of our customers interacting with Search.\",\n", " \"Apply behavioral game theory and social science understanding to get the quality work out of crowd workers from around the world\",\n", " \"Develop deep understanding of business metrics such as daily active users, query share, click share and query volume across all the relevant entry points\",\n", " \"Influence the product and business direction through metrics analyses\",\n", " \"Define and build systems and policies to ensure quality, stable, and performant code\"\n", " ],\n", " \"required_qualifications\": [\n", " \"Doctorate in Data Science, Mathematics, Statistics, Econometrics, Economics, Operations Research, Computer Science, or related field AND 5+ year(s) data-science experience.\",\n", " \"OR Master's Degree in Data Science, Mathematics, Statistics, Econometrics, Economics, Operations Research, Computer Science, or related field AND 7+ years data-science experience.\",\n", " \"OR Bachelor's Degree in Data Science, Mathematics, Statistics, Econometrics, Economics, Operations Research, Computer Science, or related field AND 10+ years data-science experience.\",\n", " \"OR equivalent experience.\"\n", " ],\n", " \"preferred_qualifications\": [\n", " \"6+ years of experience coding in Python, C++, C#, C or Java.\",\n", " \"Customer focused, strategic, drives for results, is self-motivated, and has a propensity for action.\",\n", " \"Organizational, analytical, data science skills and intuition.\",\n", " \"Problem solver: ability to solve problems that the world has not solved before\",\n", " \"Interpersonal skills: cross-group and cross-culture collaboration.\",\n", " \"Experience with real world system building and data collection, including design, coding and evaluation.\"\n", " ]\n", " },\n", " \"compensation_and_benefits\": {\n", " \"salary_or_pay_range\": \"USD $133,600 - $256,800 per year\",\n", " \"bonus_and_equity\": \"Competitive compensation package\",\n", " \"benefits\": [\n", " \"health insurance\",\n", " \"dental and vision coverage\",\n", " \"retirement plans (401k, pension)\",\n", " \"paid time off (vacation, sick days, holidays)\",\n", " \"parental leave\"\n", " ],\n", " \"perks\": [\n", " \"free food or snacks\",\n", " \"commuter benefits\",\n", " \"wellness programs\",\n", " \"learning and development stipends\",\n", " \"employee discounts\"\n", " ]\n", " }\n", "}\n" ] }, { "data": { "text/plain": [ "JobDescription(company_overview=CompanyOverview(about='Microsoft is a leading technology company responsible for delivering the quality experience to over 500M+ monthly active users around the world in Microsoft’s search engine, Bing.', mission_and_values='Empower every person and every organization on the planet to achieve more.', size='500M+ users', locations='Global', city='Redmond', state=None), role_summary=RoleSummary(title='Principal Data Scientist', team_or_department='Search + Distribution (S+D) team', role_type='Full-time', remote='N/A'), responsibilities_and_qualifications=ResponsibilitiesAndQualifications(responsibilities=['Define, invent, and deliver online and offline behavioral and human labeled metrics which accurately measure the satisfaction and success of our customers interacting with Search.', 'Apply behavioral game theory and social science understanding to get the quality work out of crowd workers from around the world', 'Develop deep understanding of business metrics such as daily active users, query share, click share and query volume across all the relevant entry points', 'Influence the product and business direction through metrics analyses', 'Define and build systems and policies to ensure quality, stable, and performant code'], required_qualifications=['Doctorate in Data Science, Mathematics, Statistics, Econometrics, Economics, Operations Research, Computer Science, or related field AND 5+ year(s) data-science experience.', \"OR Master's Degree in Data Science, Mathematics, Statistics, Econometrics, Economics, Operations Research, Computer Science, or related field AND 7+ years data-science experience.\", \"OR Bachelor's Degree in Data Science, Mathematics, Statistics, Econometrics, Economics, Operations Research, Computer Science, or related field AND 10+ years data-science experience.\", 'OR equivalent experience.'], preferred_qualifications=['6+ years of experience coding in Python, C++, C#, C or Java.', 'Customer focused, strategic, drives for results, is self-motivated, and has a propensity for action.', 'Organizational, analytical, data science skills and intuition.', 'Problem solver: ability to solve problems that the world has not solved before', 'Interpersonal skills: cross-group and cross-culture collaboration.', 'Experience with real world system building and data collection, including design, coding and evaluation.']), compensation_and_benefits=CompensationAndBenefits(salary_or_pay_range='USD $133,600 - $256,800 per year', bonus_and_equity='Competitive compensation package', benefits=['health insurance', 'dental and vision coverage', 'retirement plans (401k, pension)', 'paid time off (vacation, sick days, holidays)', 'parental leave'], perks=['free food or snacks', 'commuter benefits', 'wellness programs', 'learning and development stipends', 'employee discounts']))" ] }, "execution_count": 158, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import json\n", "\n", "def pretty_print_pydantic(obj):\n", " print(json.dumps(obj.dict(), indent=4))\n", "\n", "# Example usage\n", "pretty_print_pydantic(jobdesc)\n", "jobdesc" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('The Search + Distribution (S+D) team is the leading applied artificial '\n", " 'intelligence team at Microsoft responsible for delivering the quality '\n", " 'experience to over 500M+ monthly active users around the world in '\n", " 'Microsoft’s search engine, Bing. Our responsibilities include delivering '\n", " 'competitive search results, differentiated experiences, and product and '\n", " 'business growth. We are constantly applying the... latest state of the art '\n", " 'AI technologies to our product and also transferring this technology to '\n", " 'other groups across the company.\\n'\n", " '\\n'\n", " 'We sre seeking experienced data scientist to solve cutting-edge metrics and '\n", " 'measurement problems in the space of Search, and lead cross-team '\n", " 'initiatives. We believe metrics play a key role in executing on the strategy '\n", " 'for building the final product.\\n'\n", " '\\n'\n", " 'A critical part of the role is to advance our A/B experimentation '\n", " 'capabilities for Bing and Microsoft Copilot by introducing advanced, '\n", " 'powerful functionality at very large scale to eventually increase '\n", " 'experimenter agility and depth of insights, and reduce infrastructure cost '\n", " 'through smart design of data structures and computation methods. The role '\n", " 'requires not only skills in data science, but also knowledge in data '\n", " 'engineering and systems.\\n'\n", " '\\n'\n", " 'You will work closely with multiple teams across S+D and beyond to build a '\n", " 'measurement strategy and roadmap towards measuring how relevant, fresh, and '\n", " 'authoritative our results are while being strategically differentiated from '\n", " 'our biggest competitors. We expect you to work with Microsoft Research and '\n", " 'the rest of academia to unravel complex problems in our products and push '\n", " 'the limits of what AI can do for our customers. The world needs credible '\n", " 'alternatives to find authoritative information on the web, so there is '\n", " 'social responsibility.\\n'\n", " '\\n'\n", " 'This Principal Data Scientist position is a very strategic position part of '\n", " 'the S+D Bing Metrics and Analytics team. S+D itself is part of the broader '\n", " 'Windows and Web Experiences Team (WWE) and this position will collaborate '\n", " 'with and influence other data science and metrics groups in WWE such as '\n", " 'Edge, MS Start, Maps, Bing Ads and more. If you are passionate about working '\n", " 'on the latest and hottest areas that will help you develop skills in '\n", " 'Artificial Intelligence, Machine Learning, data science, scale systems, UX, '\n", " 'and product growth, this is the team you’re looking for!\\n'\n", " '\\n'\n", " 'Microsoft’s mission is to empower every person and every organization on the '\n", " 'planet to achieve more. As employees we come together with a growth mindset, '\n", " 'innovate to empower others, and collaborate to realize our shared goals. '\n", " 'Each day we build on our values of respect, integrity, and accountability to '\n", " 'create a culture of inclusion where everyone can thrive at work and beyond. '\n", " 'In alignment with our Microsoft values, we are committed to cultivating an '\n", " 'inclusive work environment for all employees to positively impact our '\n", " 'culture every day.\\n'\n", " '\\n'\n", " 'Responsibilities\\n'\n", " '• Define, invent, and deliver online and offline behavioral and human '\n", " 'labeled metrics which accurately measure the satisfaction and success of our '\n", " 'customers interacting with Search.\\n'\n", " '• Apply behavioral game theory and social science understanding to get the '\n", " 'quality work out of crowd workers from around the world\\n'\n", " '• Develop deep understanding of business metrics such as daily active users, '\n", " 'query share, click share and query volume across all the relevant entry '\n", " 'points\\n'\n", " '• Influence the product and business direction through metrics analyses\\n'\n", " '• Define and build systems and policies to ensure quality, stable, and '\n", " 'performant code\\n'\n", " '• Lead a team through analysis, design and code review that guarantee '\n", " 'analysis and code quality and allow more junior members to learn and grow '\n", " 'their expertise while helping the team build an inclusive interdisciplinary '\n", " 'culture where everyone can do their best work\\n'\n", " '• Make independent decisions for the team and handle difficult tradeoffs\\n'\n", " '• Translate strategy into plans that are clear and measurable, with progress '\n", " 'shared out monthly to stakeholders\\n'\n", " '• Partner effectively with program management, engineers, finance, '\n", " 'marketing, exec management, and other areas of the business\\n'\n", " '\\n'\n", " 'Qualifications\\n'\n", " '\\n'\n", " 'Required Qualifications:\\n'\n", " '• Doctorate in Data Science, Mathematics, Statistics, Econometrics, '\n", " 'Economics, Operations Research, Computer Science, or related field AND 5+ '\n", " 'year(s) data-science experience (e.g., managing structured and unstructured '\n", " 'data, applying statistical techniques and reporting results)\\n'\n", " \"• OR Master's Degree in Data Science, Mathematics, Statistics, Econometrics, \"\n", " 'Economics, Operations Research, Computer Science, or related field AND 7+ '\n", " 'years data-science experience (e.g., managing structured and unstructured '\n", " 'data, applying statistical techniques and reporting results)\\n'\n", " \"• OR Bachelor's Degree in Data Science, Mathematics, Statistics, \"\n", " 'Econometrics, Economics, Operations Research, Computer Science, or related '\n", " 'field AND 10+ years data-science experience (e.g., managing structured and '\n", " 'unstructured data, applying statistical techniques and reporting results)\\n'\n", " '• OR equivalent experience.\\n'\n", " '\\n'\n", " 'Preferred Qualifications:\\n'\n", " '• 6+ years of experience coding in Python, C++, C#, C or Java.\\n'\n", " '• Customer focused, strategic, drives for results, is self-motivated, and '\n", " 'has a propensity for action.\\n'\n", " '• Organizational, analytical, data science skills and intuition.\\n'\n", " '• Problem solver: ability to solve problems that the world has not solved '\n", " 'before\\n'\n", " '• Interpersonal skills: cross-group and cross-culture collaboration.\\n'\n", " '• Experience with real world system building and data collection, including '\n", " 'design, coding and evaluation.\\n'\n", " '\\n'\n", " 'Data Science IC5 - The typical base pay range for this role across the U.S. '\n", " 'is USD $133,600 - $256,800 per year. There is a different range applicable '\n", " 'to specific work locations, within the San Francisco Bay area and New York '\n", " 'City metropolitan area, and the base pay range for this role in those '\n", " 'locations is USD $173,200 - $282,200 per year.\\n'\n", " '\\n'\n", " 'Certain roles may be eligible for benefits and other compensation. Find '\n", " 'additional benefits and pay information here: '\n", " 'https://careers.microsoft.com/us/en/us-corporate-pay\\n'\n", " '\\n'\n", " '#WWE# #SearchDistribution# #Bing#\\n'\n", " '\\n'\n", " 'Microsoft is an equal opportunity employer. Consistent with applicable law, '\n", " 'all qualified applicants will receive consideration for employment without '\n", " 'regard to age, ancestry, citizenship, color, family or medical care leave, '\n", " 'gender identity or expression, genetic information, immigration status, '\n", " 'marital status, medical condition, national origin, physical or mental '\n", " 'disability, political affiliation, protected veteran or military status, '\n", " 'race, ethnicity, religion, sex (including pregnancy), sexual orientation, or '\n", " 'any other characteristic protected by applicable local laws, regulations and '\n", " 'ordinances. If you need assistance and/or a reasonable accommodation due to '\n", " 'a disability during the application process, read more about requesting '\n", " 'accommodations')\n" ] } ], "source": [ "import pprint\n", "pp = pprint.PrettyPrinter(width=80)\n", "pp.pprint(test_description)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "du_ds_tools", "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.11.9" } }, "nbformat": 4, "nbformat_minor": 2 }