This commit is contained in:
Maksym Solomyanov
2025-01-25 14:51:29 +01:00
13 changed files with 2237 additions and 22 deletions

View File

@@ -0,0 +1,194 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "2112166e-3629-4167-a4cb-0a1a6e549e97",
"metadata": {},
"source": [
"# Hello everyone, \n",
"The community contributions folder is super motivating. Thanks to Ed for democratising learning with this great idea of sharing. The below small piece is my novice attempt in summarizing content from wikipedia page. It is pretty straightforward, but a good learning exercise for me nevertheless. "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "947028c8-30c6-456a-8e0c-25e0de1ecbb6",
"metadata": {},
"outputs": [],
"source": [
"!pip install wikipedia"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aa18a060-6dbe-42c9-bc11-c8b079397d6b",
"metadata": {},
"outputs": [],
"source": [
"# Import statements\n",
"import os\n",
"import requests\n",
"from dotenv import load_dotenv\n",
"from IPython.display import Markdown, display\n",
"from openai import OpenAI\n",
"import wikipedia\n",
"import warnings"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8d9c128d-ed7d-4e58-8cd1-1468242c7967",
"metadata": {},
"outputs": [],
"source": [
"#To supress a warning from wikipedia module when there are multiple options.\n",
"warnings.filterwarnings(\"ignore\", category=UserWarning, module=\"wikipedia\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5371f405-e628-4b6a-a5ab-5774c1431749",
"metadata": {},
"outputs": [],
"source": [
"# Load environment variables in a file called .env\n",
"\n",
"load_dotenv()\n",
"api_key = os.getenv('OPENAI_API_KEY')\n",
"\n",
"# Check the key\n",
"\n",
"if not api_key:\n",
" print(\"No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!\")\n",
"elif not api_key.startswith(\"sk-proj-\"):\n",
" print(\"An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook\")\n",
"elif api_key.strip() != api_key:\n",
" print(\"An API key was found, but it looks like it might have space or tab characters at the start or end - please remove them - see troubleshooting notebook\")\n",
"else:\n",
" print(\"API key found and looks good so far!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e6610504-bd7b-459f-9722-0044b3101e05",
"metadata": {},
"outputs": [],
"source": [
"openai = OpenAI()\n",
"\n",
"# If this doesn't work, try Kernel menu >> Restart Kernel and Clear Outputs Of All Cells, then run the cells from the top of this notebook down.\n",
"# If it STILL doesn't work (horrors!) then please see the troubleshooting notebook, or try the below line instead:\n",
"# openai = OpenAI(api_key=\"your-key-here-starting-sk-proj-\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ac37741a-2608-4760-8ba8-163fb9155f0f",
"metadata": {},
"outputs": [],
"source": [
"class Wikipedia:\n",
" def __init__(self, searchText):\n",
" \"\"\"\n",
" Create this object to extract the summary of wikipedia page for a text entered by user\n",
" \"\"\"\n",
" self.searchText = searchText\n",
" self.summary_text = None\n",
" self.user_prompt = None\n",
" \n",
" self._fetch_summary()\n",
"\n",
" def _fetch_summary(self):\n",
" \"\"\"\n",
" Fetches the summary from wikipedia page based on user entered search text and sets user prompt accordingly\n",
" \"\"\"\n",
" try:\n",
" # Try to get the summary of the text from Wikipedia based on user entered text. Using starightforward summary module in wikipedia.\n",
" self.summary_text = wikipedia.summary(self.searchText)\n",
" self.user_prompt = f\"You are looking a summary extract from a wikipedia page. The content is as follows\\n {self.summary_text}.\\nProvide \\\n",
" a summary taking key points from each sections listed on the page\"\n",
" except wikipedia.DisambiguationError as e:\n",
" #Modify user and system prompts if there are multiple options for a user search text\n",
" self.user_prompt = f\"You have received quite a few options {e.options} for the keyword {self.searchText}. Please request user to choose one of them\"\n",
" except wikipedia.PageError:\n",
" #To handle when there is no page\n",
" self.user_prompt = f\"There is no wiki page for {self.searchText}. Apparently it is not your fault!\"\n",
" except Exception as e:\n",
" # To handle any other exceptions\n",
" self.user_prompt = f\"Sorry, something seems to be wrong on my end. Please try again later\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "143c203e-bb99-49c6-89a2-2a32ea429719",
"metadata": {},
"outputs": [],
"source": [
"# Our by-now familiar sumamrize function\n",
"def summarize(searchText):\n",
" wiki = Wikipedia(searchText)\n",
" system_prompt = f\"You are an assitant trying to summarize content from Wikipedia. You will have three scenarios to handle your responses \\\n",
" 1. You will have the summary text content and you will just show that to user\\\n",
" 2. You will have multiple options for the user entered keyword, and you will respond by asking user to choose from that and request again \\\n",
" 3. You will not have the content due to a page not found error. Respond accordingly.\\\n",
" Respond all of these in Markdown format.\"\n",
" messages = [\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": wiki.user_prompt}\n",
" ]\n",
" response = openai.chat.completions.create(\n",
" model = \"gpt-4o-mini\",\n",
" messages = messages\n",
" )\n",
" return response.choices[0].message.content\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b61532fc-189c-4cd8-9402-93d8d8fa8c59",
"metadata": {},
"outputs": [],
"source": [
"summary = summarize(\"mukhari\")\n",
"display(Markdown(summary))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5c3f05f6-acb5-41e4-a521-8d8b8ace0192",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -0,0 +1,356 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "31d3c4a4-5442-4074-b812-42d60e0a0c04",
"metadata": {},
"outputs": [],
"source": [
"#In this example we will fetch the job description by pasting the URL,then we upload CV. Only then ChatGPT will\n",
"#analyze CV against the fetched job description. If the CV is a good match then it will write a cover letter.\n",
"\n",
"#If \n",
" ##job posting url is fake/random text or \n",
" ##job posting is fake/random tex or \n",
" ##CV is fake/random text\n",
"#then ChatGPT will not analyze CV, it will give a generic response to enter the info correctly."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bc2eafe6-5255-4317-8ddd-a93695296043",
"metadata": {},
"outputs": [],
"source": [
"pip install PyPDF2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cf45e9d5-4913-416c-9880-5be60a96c0e6",
"metadata": {},
"outputs": [],
"source": [
"# Imports\n",
"import os\n",
"import io\n",
"import time\n",
"import requests\n",
"import PyPDF2\n",
"from dotenv import load_dotenv\n",
"from IPython.display import Markdown, display\n",
"from bs4 import BeautifulSoup\n",
"from openai import OpenAI\n",
"from ipywidgets import Textarea, FileUpload, Button, VBox, HTML"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "af8fea69-60aa-430c-a16c-8757b487e07a",
"metadata": {},
"outputs": [],
"source": [
"load_dotenv(override=True)\n",
"api_key = os.getenv('OPENAI_API_KEY')\n",
"\n",
"# Check the key\n",
"\n",
"if not api_key:\n",
" print(\"No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!\")\n",
"elif not api_key.startswith(\"sk-proj-\"):\n",
" print(\"An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook\")\n",
"elif api_key.strip() != api_key:\n",
" print(\"An API key was found, but it looks like it might have space or tab characters at the start or end - please remove them - see troubleshooting notebook\")\n",
"else:\n",
" print(\"API key found and looks good so far!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "daee94d2-f82b-43f0-95d1-15370eda1bc7",
"metadata": {},
"outputs": [],
"source": [
"openai = OpenAI()\n",
"\n",
"# If this doesn't work, try Kernel menu >> Restart Kernel and Clear Outputs Of All Cells, then run the cells from the top of this notebook down.\n",
"# If it STILL doesn't work (horrors!) then please see the Troubleshooting notebook in this folder for full instructions"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0712dd1d-b6bc-41c6-84ec-d965f696f7aa",
"metadata": {},
"outputs": [],
"source": [
"# Step 1: Create your prompts\n",
"\n",
"system_prompt = \"You are an assistant who analyzes user's CV against the job description \\\n",
" and provide a short summary if the user is fit for this job. If the user is fit for the job \\\n",
" write a cover letter for the user to apply for the job. Keep the cover letter professional, short, \\\n",
" and formal. \\\n",
" Important things to notice before analyzing CV:\\\n",
" 1. Always check if the CV is actually a CV or just random text\\\n",
" 2. Check if the job description fetched from the website is the job description or not\\\n",
" and ignore text related to navigation\\\n",
" 3. Also check the link of the job posting, if it actually resembles a job posting or is just random \\\n",
" fake website\\\n",
" 4. if any one of these two checks fails, do not analyze the CV against the Job description and give an\\\n",
" appropriate response as you think\\\n",
" 5. Always respond in Markdown.\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "70c972a6-8af6-4ff2-a338-6d7ba90e2045",
"metadata": {},
"outputs": [],
"source": [
"# A class to represent a Webpage\n",
"# If you're not familiar with Classes, check out the \"Intermediate Python\" notebook\n",
"\n",
"# Some websites need you to use proper headers when fetching them:\n",
"headers = {\n",
" \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n",
"}\n",
"\n",
"class Website:\n",
"\n",
" def __init__(self, url):\n",
" \"\"\"\n",
" Create this Website object from the given url using the BeautifulSoup library\n",
" \"\"\"\n",
" self.url = url\n",
" response = requests.get(url, headers=headers)\n",
" soup = BeautifulSoup(response.content, 'html.parser')\n",
" self.title = soup.title.string if soup.title else \"No title found\"\n",
" for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
" irrelevant.decompose()\n",
" self.text = soup.body.get_text(separator=\"\\n\", strip=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "426dfd9b-3446-4543-9819-63040abd9644",
"metadata": {},
"outputs": [],
"source": [
"for_user_prompt = {\n",
" 'job_posting_url':'',\n",
" 'job_posting': '',\n",
" 'cv_text': ''\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "79d9ccd6-f5fe-4ce8-982c-7235d2cf6a9f",
"metadata": {},
"outputs": [],
"source": [
"# Create widgets - to create a box for the job posting text\n",
"job_posting_url_area = Textarea(\n",
" placeholder='Paste the URL of the job posting here, ONLY URL PLEASE',\n",
" description='Fetching job:',\n",
" disabled=False,\n",
" layout={'width': '800px', 'height': '50px'}\n",
")\n",
"\n",
"status_job_posting = HTML(value=\"<b>Status:</b> Waiting for inputs...\")\n",
"\n",
"# Create Submit Buttons\n",
"fetch_job_posting_button = Button(description='Fetch Job Posting', button_style='primary')\n",
"\n",
"def fetch_job_posting_action(b):\n",
" for_user_prompt['job_posting_url'] = job_posting_url_area.value\n",
" if for_user_prompt['job_posting_url']:\n",
" ed = Website(for_user_prompt['job_posting_url'])\n",
" status_job_posting.value = \"<b>Status:</b> Job posting fetched successfully!\"\n",
" fetch_job_posting_button.button_style='success'\n",
" for_user_prompt['job_posting']=ed.text\n",
" else:\n",
" status_job_posting.value = \"<b>Status:</b> Please enter a job posting url before submitting.\"\n",
"\n",
"# Attach actions to buttons\n",
"fetch_job_posting_button.on_click(fetch_job_posting_action)\n",
"\n",
"# Layout\n",
"job_posting_box = VBox([job_posting_url_area, fetch_job_posting_button])\n",
"\n",
"# Display all widgets\n",
"display(VBox([\n",
" HTML(value=\"<h2>Input Job Posting Url</h2>\"),\n",
" job_posting_box,\n",
" status_job_posting\n",
"]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "58d42786-1580-4d3f-b44f-5c52250c2935",
"metadata": {},
"outputs": [],
"source": [
"# Print fetched job description\n",
"\n",
"#print(for_user_prompt['job_posting'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cd258dec-9b57-40ce-b37c-2627acbcb5af",
"metadata": {},
"outputs": [],
"source": [
"# Define file upload for CV\n",
"cv_upload = FileUpload(\n",
" accept='.pdf', # Only accept PDF files\n",
" multiple=False, # Only allow single file selection\n",
" description='Upload CV (PDF)'\n",
")\n",
"\n",
"status = HTML(value=\"<b>Status:</b> Waiting for inputs...\")\n",
"\n",
"# Create Submit Buttons\n",
"submit_cv_button = Button(description='Submit CV', button_style='success')\n",
"\n",
"# Functions\n",
"def submit_cv_action(change):\n",
"\n",
" if not for_user_prompt['cv_text']:\n",
" status.value = \"<b>Status:</b> Please upload a CV before submitting.\"\n",
" \n",
" if cv_upload.value:\n",
" # Get the uploaded file\n",
" uploaded_file = cv_upload.value[0]\n",
" content = io.BytesIO(uploaded_file['content'])\n",
" \n",
" try:\n",
" pdf_reader = PyPDF2.PdfReader(content) \n",
" cv_text = \"\"\n",
" for page in pdf_reader.pages: \n",
" cv_text += page.extract_text() \n",
" \n",
" # Store CV text in for_user_prompt\n",
" for_user_prompt['cv_text'] = cv_text\n",
" status.value = \"<b>Status:</b> CV uploaded and processed successfully!\"\n",
" except Exception as e:\n",
" status.value = f\"<b>Status:</b> Error processing PDF: {str(e)}\"\n",
"\n",
" time.sleep(0.5) # Short pause between upload and submit messages to display both\n",
" \n",
" if for_user_prompt['cv_text']:\n",
" #print(\"CV Submitted:\")\n",
" #print(for_user_prompt['cv_text'])\n",
" status.value = \"<b>Status:</b> CV submitted successfully!\"\n",
" \n",
"\n",
"# Attach actions to buttons\n",
"submit_cv_button.on_click(submit_cv_action)\n",
"\n",
"# Layout\n",
"cv_buttons = VBox([submit_cv_button])\n",
"\n",
"# Display all widgets\n",
"display(VBox([\n",
" HTML(value=\"<h2>Import CV and submit</h2>\"),\n",
" cv_upload,\n",
" cv_buttons,\n",
" status\n",
"]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a7dd22a4-ca7b-4b8c-a328-6205cec689cb",
"metadata": {},
"outputs": [],
"source": [
"# Prepare the user prompt that we will send to open ai (added URL for the context)\n",
"user_prompt = f\"\"\"\n",
"Job Posting: \n",
"{for_user_prompt['job_posting']}\n",
"\n",
"CV: \n",
"{for_user_prompt['cv_text']}\n",
"\n",
"Url:\n",
"{for_user_prompt['job_posting_url']}\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "82b71c1a-895a-48e7-a945-13e615bb0096",
"metadata": {},
"outputs": [],
"source": [
"# Define messages with system_prompt and user_prompt\n",
"def messages_for(system_prompt_input, user_prompt_input):\n",
" return [\n",
" {\"role\": \"system\", \"content\": system_prompt_input},\n",
" {\"role\": \"user\", \"content\": user_prompt_input}\n",
" ]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "854dc42e-2bbd-493b-958f-c20484908300",
"metadata": {},
"outputs": [],
"source": [
"# And now: call the OpenAI API. \n",
"response = openai.chat.completions.create(\n",
" model = \"gpt-4o-mini\",\n",
" messages = messages_for(system_prompt, user_prompt)\n",
")\n",
"\n",
"# Response is provided in Markdown and displayed accordingly\n",
"display(Markdown(response.choices[0].message.content))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "758d2cbe-0f80-4572-8724-7cba77f701dd",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -405,6 +405,14 @@
"from diagnostics import Diagnostics\n",
"Diagnostics().run()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e1955b9a-d344-4782-b448-2770d0edd90c",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {