Spaces:
Sleeping
Sleeping
File size: 11,412 Bytes
5fdb69e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
{
"cells": [
{
"cell_type": "markdown",
"id": "a98030af-fcd1-4d63-a36e-38ba053498fa",
"metadata": {},
"source": [
"# Week 2 Practice Gradio by Creating Brochure\n",
"\n",
"- **Author**: [stoneskin](https://www.github.com/stoneskin)"
]
},
{
"cell_type": "markdown",
"id": "1c104f45",
"metadata": {},
"source": [
"## Implementation\n",
"\n",
"- Use OpenRouter.ai for all different types of LLM models, include many free models from Google,Meta and Deepseek\n",
"\n",
"Full code for the Week2 Gradio practice is below:"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "b8d3e1a1-ba54-4907-97c5-30f89a24775b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"API key looks good so far\n"
]
}
],
"source": [
"import os\n",
"import json\n",
"import requests\n",
"from bs4 import BeautifulSoup\n",
"from typing import List\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import gradio as gr \n",
"\n",
"load_dotenv(override=True)\n",
"\n",
"api_key = os.getenv('Open_Router_Key')\n",
"if api_key and api_key.startswith('sk-or-v1') and len(api_key)>10:\n",
" print(\"API key looks good so far\")\n",
"else:\n",
" print(\"There might be a problem with your API key? Please visit the troubleshooting notebook!\")\n",
" \n",
" \n",
"openai = OpenAI(\n",
" api_key=api_key,\n",
" base_url=\"https://openrouter.ai/api/v1\"\n",
")\n",
"\n",
"MODEL_Gemini2FlashThink = 'google/gemini-2.0-flash-thinking-exp:free'\n",
"MODEL_Gemini2Pro ='google/gemini-2.0-pro-exp-02-05:free'\n",
"MODEL_Gemini2FlashLite = 'google/gemini-2.0-flash-lite-preview-02-05:free'\n",
"MODEL_Meta_Llama33 ='meta-llama/llama-3.3-70b-instruct:free'\n",
"MODEL_Deepseek_V3='deepseek/deepseek-chat:free'\n",
"MODEL_Deepseek_R1='deepseek/deepseek-r1-distill-llama-70b:free'\n",
"MODEL_Qwen_vlplus='qwen/qwen-vl-plus:free'\n",
"MODEL_OpenAi_o3mini = 'openai/o3-mini'\n",
"MODEL_OpenAi_4o = 'openai/gpt-4o-2024-11-20'\n",
"MODEL_Claude_Haiku = 'anthropic/claude-3.5-haiku-20241022'\n",
"\n",
"\n",
"\n",
"\n",
" \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "24866034",
"metadata": {},
"outputs": [],
"source": [
"MODEL=MODEL_Gemini2Pro # choice the model you want to use\n",
"\n",
"####################\n",
"system_prompt = \"You are an assistant that analyzes the contents of several relevant pages from a company website \\\n",
"and creates a short humorous, entertaining, jokey brochure about the company for prospective customers, investors and recruits. Respond in markdown.\\\n",
"Include details of company culture, customers and careers/jobs if you have the information.\"\n",
"\n",
"##############################\n",
"link_system_prompt = \"You are provided with a list of links found on a webpage. \\\n",
"You are able to decide which of the links would be most relevant to include in a brochure about the company, \\\n",
"such as links to an About page, or a Company page, or Careers/Jobs pages.\\n\"\n",
"link_system_prompt += \"You should respond in JSON as in this example:\"\n",
"link_system_prompt += \"\"\"\n",
"{\n",
" \"links\": [\n",
" {\"type\": \"about page\", \"url\": \"https://full.url/goes/here/about\"},\n",
" {\"type\": \"careers page\": \"url\": \"https://another.full.url/careers\"}\n",
" ]\n",
"}\n",
"\"\"\"\n",
"\n",
"##############################\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",
"##############################\n",
"class Website:\n",
" \"\"\"\n",
" A utility class to represent a Website that we have scraped, now with links\n",
" \"\"\"\n",
"\n",
" def __init__(self, url):\n",
" self.url = url\n",
" response = requests.get(url, headers=headers)\n",
" self.body = response.content\n",
" soup = BeautifulSoup(self.body, 'html.parser')\n",
" self.title = soup.title.string if soup.title else \"No title found\"\n",
" if soup.body:\n",
" for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
" irrelevant.decompose()\n",
" self.text = soup.body.get_text(separator=\"\\n\", strip=True)\n",
" else:\n",
" self.text = \"\"\n",
" links = [link.get('href') for link in soup.find_all('a')]\n",
" self.links = [link for link in links if link]\n",
"\n",
" def get_contents(self):\n",
" return f\"Webpage Title:\\n{self.title}\\nWebpage Contents:\\n{self.text}\\n\\n\"\n",
" \n",
"##############################\n",
"def get_links_user_prompt(website):\n",
" user_prompt = f\"Here is the list of links on the website of {website.url} - \"\n",
" user_prompt += \"please decide which of these are relevant web links for a brochure about the company, respond with the full https URL in JSON format. \\\n",
"Do not include Terms of Service, Privacy, email links.\\n\"\n",
" user_prompt += \"Links (some might be relative links):\\n\"\n",
" user_prompt += \"\\n\".join(website.links)\n",
" return user_prompt\n",
"\n",
"##############################\n",
"def get_links(url):\n",
" website = Website(url)\n",
" response = openai.chat.completions.create(\n",
" model=MODEL,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": link_system_prompt},\n",
" {\"role\": \"user\", \"content\": get_links_user_prompt(website)}\n",
" ],\n",
" response_format={\"type\": \"json_object\"}\n",
" )\n",
" result = response.choices[0].message.content\n",
" print(\"get_links:\", result)\n",
" return json.loads(result)\n",
"\n",
"##############################\n",
"def get_brochure_user_prompt(company_name, url):\n",
" user_prompt = f\"You are looking at a company called: {company_name}\\n\"\n",
" user_prompt += f\"Here are the contents of its landing page and other relevant pages; use this information to build a short brochure of the company in markdown.\\n\"\n",
" user_prompt += get_all_details(url)\n",
" user_prompt = user_prompt[:5_000] # Truncate if more than 5,000 characters\n",
" return user_prompt\n",
"\n",
"##############################\n",
"def get_all_details(url):\n",
" print(\"get_all_details:\", url) \n",
" result = \"Landing page:\\n\"\n",
" result += Website(url).get_contents()\n",
" links = get_links(url)\n",
" print(\"Found links:\", links)\n",
" for link in links[\"links\"]:\n",
" result += f\"\\n\\n{link['type']}\\n\"\n",
" result += Website(link[\"url\"]).get_contents()\n",
" return result"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "82abe132",
"metadata": {},
"outputs": [],
"source": [
"########### modified stream brochure function for gradio ###################\n",
"def stream_brochure(company_name, url):\n",
" stream = openai.chat.completions.create(\n",
" model=MODEL,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": get_brochure_user_prompt(company_name, url)}\n",
" ],\n",
" stream=True\n",
" )\n",
" \n",
"\n",
" result = \"\"\n",
" for chunk in stream:\n",
" result += chunk.choices[0].delta.content or \"\"\n",
" yield result"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "902f203b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"* Running on local URL: http://127.0.0.1:7872\n",
"\n",
"To create a public link, set `share=True` in `launch()`.\n"
]
},
{
"data": {
"text/html": [
"<div><iframe src=\"http://127.0.0.1:7872/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": []
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"get_all_details: https://mlccc.herokuapp.com/\n",
"get_links: {\n",
" \"links\": [\n",
" {\"type\": \"about page\", \"url\": \"https://mlccc.herokuapp.com/about.html\"},\n",
" {\"type\": \"programs\", \"url\": \"https://mlccc.herokuapp.com/program.html\"},\n",
" {\"type\": \"camps\", \"url\": \"https://mlccc.herokuapp.com/camps.html\"},\n",
" {\"type\": \"community\", \"url\": \"https://mlccc.herokuapp.com/community.html\"},\n",
" {\"type\": \"support\", \"url\": \"https://mlccc.herokuapp.com/support.html\"},\n",
" {\"type\": \"press\", \"url\": \"https://mlccc.herokuapp.com/press.html\"},\n",
" {\"type\": \"newsletter\", \"url\": \"https://mlccc.herokuapp.com/newsletter.html\"},\n",
" {\"type\": \"testimonials\", \"url\": \"https://mlccc.herokuapp.com/testimonial.html\"}\n",
" ]\n",
"}\n",
"Found links: {'links': [{'type': 'about page', 'url': 'https://mlccc.herokuapp.com/about.html'}, {'type': 'programs', 'url': 'https://mlccc.herokuapp.com/program.html'}, {'type': 'camps', 'url': 'https://mlccc.herokuapp.com/camps.html'}, {'type': 'community', 'url': 'https://mlccc.herokuapp.com/community.html'}, {'type': 'support', 'url': 'https://mlccc.herokuapp.com/support.html'}, {'type': 'press', 'url': 'https://mlccc.herokuapp.com/press.html'}, {'type': 'newsletter', 'url': 'https://mlccc.herokuapp.com/newsletter.html'}, {'type': 'testimonials', 'url': 'https://mlccc.herokuapp.com/testimonial.html'}]}\n"
]
}
],
"source": [
"view = gr.Interface(\n",
" fn=stream_brochure,\n",
" inputs=[gr.Textbox(label=\"company Name\"), gr.Textbox(label=\"URL\")],\n",
" outputs=[gr.Markdown(label=\"Response:\")],\n",
" flagging_mode=\"never\"\n",
")\n",
"view.launch()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "llms",
"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
}
|