From 4bad3a828f3e3ce301be028d93d501fac6ed9c56 Mon Sep 17 00:00:00 2001 From: Petri Alapiessa Date: Fri, 17 Jan 2025 11:21:51 +0200 Subject: [PATCH] Example ready --- .../day1-webscraping-playwright.ipynb | 434 +----------------- 1 file changed, 11 insertions(+), 423 deletions(-) diff --git a/week1/community-contributions/day1-webscraping-playwright.ipynb b/week1/community-contributions/day1-webscraping-playwright.ipynb index e73ad69..75cc7d8 100644 --- a/week1/community-contributions/day1-webscraping-playwright.ipynb +++ b/week1/community-contributions/day1-webscraping-playwright.ipynb @@ -1,31 +1,5 @@ { "cells": [ - { - "cell_type": "markdown", - "id": "d15d8294-3328-4e07-ad16-8a03e9bbfdb9", - "metadata": {}, - "source": [ - "# Instant Gratification\n", - "\n", - "## Your first Frontier LLM Project!\n", - "\n", - "Let's build a useful LLM solution - in a matter of minutes.\n", - "\n", - "By the end of this course, you will have built an autonomous Agentic AI solution with 7 agents that collaborate to solve a business problem. All in good time! We will start with something smaller...\n", - "\n", - "Our goal is to code a new kind of Web Browser. Give it a URL, and it will respond with a summary. The Reader's Digest of the internet!!\n", - "\n", - "Before starting, you should have completed the setup for [PC](../SETUP-PC.md) or [Mac](../SETUP-mac.md) and you hopefully launched this jupyter lab from within the project root directory, with your environment activated.\n", - "\n", - "## If you're new to Jupyter Lab\n", - "\n", - "Welcome to the wonderful world of Data Science experimentation! Once you've used Jupyter Lab, you'll wonder how you ever lived without it. Simply click in each \"cell\" with code in it, such as the cell immediately below this text, and hit Shift+Return to execute that cell. As you wish, you can add a cell with the + button in the toolbar, and print values of variables, or try out variations. \n", - "\n", - "I've written a notebook called [Guide to Jupyter](Guide%20to%20Jupyter.ipynb) to help you get more familiar with Jupyter Labs, including adding Markdown comments, using `!` to run shell commands, and `tqdm` to show progress.\n", - "\n", - "If you prefer to work in IDEs like VSCode or Pycharm, they both work great with these lab notebooks too. \n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -103,98 +77,6 @@ "# openai = OpenAI(api_key=\"your-key-here-starting-sk-proj-\")" ] }, - { - "cell_type": "markdown", - "id": "442fc84b-0815-4f40-99ab-d9a5da6bda91", - "metadata": {}, - "source": [ - "# Let's make a quick call to a Frontier model to get started, as a preview!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a58394bf-1e45-46af-9bfd-01e24da6f49a", - "metadata": {}, - "outputs": [], - "source": [ - "# To give you a preview -- calling OpenAI with these messages is this easy:\n", - "\n", - "message = \"Hello, GPT! This is my first ever message to you! Hi!\"\n", - "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=[{\"role\":\"user\", \"content\":message}])\n", - "print(response.choices[0].message.content)" - ] - }, - { - "cell_type": "markdown", - "id": "2aa190e5-cb31-456a-96cc-db109919cd78", - "metadata": {}, - "source": [ - "## OK onwards with our first project" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c5e793b2-6775-426a-a139-4848291d0463", - "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": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97", - "metadata": {}, - "outputs": [], - "source": [ - "# Let's try one out. Change the website and add print statements to follow along.\n", - "\n", - "ed = Website(\"https://edwarddonner.com\")\n", - "print(ed.title)\n", - "print(ed.text)" - ] - }, - { - "cell_type": "markdown", - "id": "6a478a0c-2c53-48ff-869c-4d08199931e1", - "metadata": {}, - "source": [ - "## Types of prompts\n", - "\n", - "You may know this already - but if not, you will get very familiar with it!\n", - "\n", - "Models like GPT4o have been trained to receive instructions in a particular way.\n", - "\n", - "They expect to receive:\n", - "\n", - "**A system prompt** that tells them what task they are performing and what tone they should use\n", - "\n", - "**A user prompt** -- the conversation starter that they should reply to" - ] - }, { "cell_type": "code", "execution_count": null, @@ -227,193 +109,6 @@ " return user_prompt" ] }, - { - "cell_type": "code", - "execution_count": null, - "id": "26448ec4-5c00-4204-baec-7df91d11ff2e", - "metadata": {}, - "outputs": [], - "source": [ - "print(user_prompt_for(ed))" - ] - }, - { - "cell_type": "markdown", - "id": "ea211b5f-28e1-4a86-8e52-c0b7677cadcc", - "metadata": {}, - "source": [ - "## Messages\n", - "\n", - "The API from OpenAI expects to receive messages in a particular structure.\n", - "Many of the other APIs share this structure:\n", - "\n", - "```\n", - "[\n", - " {\"role\": \"system\", \"content\": \"system message goes here\"},\n", - " {\"role\": \"user\", \"content\": \"user message goes here\"}\n", - "]\n", - "\n", - "To give you a preview, the next 2 cells make a rather simple call - we won't stretch the might GPT (yet!)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5", - "metadata": {}, - "outputs": [], - "source": [ - "messages = [\n", - " {\"role\": \"system\", \"content\": \"You are a snarky assistant\"},\n", - " {\"role\": \"user\", \"content\": \"What is 2 + 2?\"}\n", - "]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "21ed95c5-7001-47de-a36d-1d6673b403ce", - "metadata": {}, - "outputs": [], - "source": [ - "# To give you a preview -- calling OpenAI with system and user messages:\n", - "\n", - "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", - "print(response.choices[0].message.content)" - ] - }, - { - "cell_type": "markdown", - "id": "d06e8d78-ce4c-4b05-aa8e-17050c82bb47", - "metadata": {}, - "source": [ - "## And now let's build useful messages for GPT-4o-mini, using a function" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0134dfa4-8299-48b5-b444-f2a8c3403c88", - "metadata": {}, - "outputs": [], - "source": [ - "# See how this function creates exactly the format above\n", - "\n", - "def messages_for(website):\n", - " return [\n", - " {\"role\": \"system\", \"content\": system_prompt},\n", - " {\"role\": \"user\", \"content\": user_prompt_for(website)}\n", - " ]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "36478464-39ee-485c-9f3f-6a4e458dbc9c", - "metadata": {}, - "outputs": [], - "source": [ - "# Try this out, and then try for a few more websites\n", - "\n", - "messages_for(ed)" - ] - }, - { - "cell_type": "markdown", - "id": "16f49d46-bf55-4c3e-928f-68fc0bf715b0", - "metadata": {}, - "source": [ - "## Time to bring it together - the API for OpenAI is very simple!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "905b9919-aba7-45b5-ae65-81b3d1d78e34", - "metadata": {}, - "outputs": [], - "source": [ - "# And now: call the OpenAI API. You will get very familiar with this!\n", - "\n", - "def summarize(url):\n", - " website = Website(url)\n", - " response = openai.chat.completions.create(\n", - " model = \"gpt-4o-mini\",\n", - " messages = messages_for(website)\n", - " )\n", - " return response.choices[0].message.content" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5", - "metadata": {}, - "outputs": [], - "source": [ - "summarize(\"https://edwarddonner.com\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3d926d59-450e-4609-92ba-2d6f244f1342", - "metadata": {}, - "outputs": [], - "source": [ - "# A function to display this nicely in the Jupyter output, using markdown\n", - "\n", - "def display_summary(url):\n", - " summary = summarize(url)\n", - " display(Markdown(summary))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3018853a-445f-41ff-9560-d925d1774b2f", - "metadata": {}, - "outputs": [], - "source": [ - "display_summary(\"https://edwarddonner.com\")" - ] - }, - { - "cell_type": "markdown", - "id": "b3bcf6f4-adce-45e9-97ad-d9a5d7a3a624", - "metadata": {}, - "source": [ - "# Let's try more websites\n", - "\n", - "Note that this will only work on websites that can be scraped using this simplistic approach.\n", - "\n", - "Websites that are rendered with Javascript, like React apps, won't show up. See the community-contributions folder for a Selenium implementation that gets around this. You'll need to read up on installing Selenium (ask ChatGPT!)\n", - "\n", - "Also Websites protected with CloudFront (and similar) may give 403 errors - many thanks Andy J for pointing this out.\n", - "\n", - "But many websites will work just fine!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "45d83403-a24c-44b5-84ac-961449b4008f", - "metadata": {}, - "outputs": [], - "source": [ - "display_summary(\"https://cnn.com\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "75e9fd40-b354-4341-991e-863ef2e59db7", - "metadata": {}, - "outputs": [], - "source": [ - "display_summary(\"https://anthropic.com\")" - ] - }, { "cell_type": "markdown", "id": "36ed9f14-b349-40e9-a42c-b367e77f8bda", @@ -421,29 +116,7 @@ "source": [ "## An extra exercise for those who enjoy web scraping\n", "\n", - "You may notice that if you try `display_summary(\"https://openai.com\")` - it doesn't work! That's because OpenAI has a fancy website that uses Javascript. There are many ways around this that some of you might be familiar with. For example, Selenium is a hugely popular framework that runs a browser behind the scenes, renders the page, and allows you to query it. If you have experience with Selenium, Playwright or similar, then feel free to improve the Website class to use them. In the community-contributions folder, you'll find an example Selenium solution from a student (thank you!)" - ] - }, - { - "cell_type": "markdown", - "id": "eeab24dc-5f90-4570-b542-b0585aca3eb6", - "metadata": {}, - "source": [ - "# Sharing your code\n", - "\n", - "I'd love it if you share your code afterwards so I can share it with others! You'll notice that some students have already made changes (including a Selenium implementation) which you will find in the community-contributions folder. If you'd like add your changes to that folder, submit a Pull Request with your new versions in that folder and I'll merge your changes.\n", - "\n", - "If you're not an expert with git (and I am not!) then GPT has given some nice instructions on how to submit a Pull Request. It's a bit of an involved process, but once you've done it once it's pretty clear. As a pro-tip: it's best if you clear the outputs of your Jupyter notebooks (Edit >> Clean outputs of all cells, and then Save) for clean notebooks.\n", - "\n", - "PR instructions courtesy of an AI friend: https://chatgpt.com/share/670145d5-e8a8-8012-8f93-39ee4e248b4c" - ] - }, - { - "cell_type": "markdown", - "id": "0f62a788", - "metadata": {}, - "source": [ - "# **Web Scraping for JavaScript Website with Playwright**" + "You may notice that if you try the course example with \"https://openai.com\" - it doesn't work! That's because OpenAI has a fancy website that uses Javascript. There are many ways around this that some of you might be familiar with. Below an example created with Playwright." ] }, { @@ -453,8 +126,6 @@ "metadata": {}, "outputs": [], "source": [ - "#! pip install grpcio==1.68.1\n", - "#! pip install grpcio-status==1.68.1\n", "! pip install playwright\n", "! playwright install" ] @@ -477,6 +148,7 @@ "class Website:\n", " title: str\n", " text: str\n", + " url: str\n", "\n", " def __init__(self, url):\n", " self.url = url\n", @@ -501,112 +173,28 @@ " async with async_playwright() as playwright:\n", " await self.run(playwright) \n", " \n", - "\n", + "def messages_for(website):\n", + " return [\n", + " {\"role\": \"system\", \"content\": system_prompt},\n", + " {\"role\": \"user\", \"content\": user_prompt_for(website)}\n", + " ]\n", "\n", "if __name__ == \"__main__\":\n", - " site = Website('https://www.canva.com')\n", + " site = Website('https://openai.com')\n", " asyncio.run(site.main())\n", - " print(f\"Title: {site.title}\")\n", - " print(f\"Content: {site.text}\")\n", - " \n", - "#web = Website(\"https://edwarddonner.com/\")\n", - "\n", - "#loop = asyncio.get_event_loop()\n", - "#loop.run_until_complete(Website.main(web))\n", - "\n", - "#print(f\"Title: {web.title}\")\n", - "#print(f\"Content: {web.text}\")\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "90ca6dd0", - "metadata": {}, - "outputs": [], - "source": [ - "import asyncio\n", - "from playwright.async_api import async_playwright\n", - "import nest_asyncio\n", - "\n", - "\n", - "\n", - "class Website:\n", - " title: str\n", - " text: str\n", - "\n", - " def __init__(self, title, text):\n", - " \n", - " self.title = title\n", - " self.text = text\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "947eac30", - "metadata": {}, - "outputs": [], - "source": [ - "chrome_path = \"C:/Program Files/Google/Chrome/Application/chrome.exe\"\n", - "url = \"https://www.canva.com/\"\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2cba8c91", - "metadata": {}, - "outputs": [], - "source": [ - "def new_summary(url, chrome_path):\n", - " \n", " response = openai.chat.completions.create(\n", " model = \"gpt-4o-mini\",\n", - " messages = messages_for(web)\n", + " messages = messages_for(site)\n", " )\n", "\n", " web_summary = response.choices[0].message.content\n", - " \n", - " return display(Markdown(web_summary))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "da7f7b16", - "metadata": {}, - "outputs": [], - "source": [ - "new_summary(url, chrome_path)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7880ce6a", - "metadata": {}, - "outputs": [], - "source": [ - "url = \"https://openai.com\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "337b06da", - "metadata": {}, - "outputs": [], - "source": [ - "new_summary(url, chrome_path)" + " display(Markdown(web_summary))" ] }, { "cell_type": "code", "execution_count": null, - "id": "9a5d69ea", + "id": "69218dec-749c-412d-84a0-40a10fd80c73", "metadata": {}, "outputs": [], "source": []