{ "cells": [ { "cell_type": "code", "execution_count": 23, "id": "bbb5d7a3-c47a-4b2e-9ee0-5cf0b0cfd808", "metadata": {}, "outputs": [], "source": [ "import re\n", "from typing import Union\n", "\n", "import aiohttp\n", "from bs4 import BeautifulSoup\n", "from pydantic import BaseModel\n", "from tqdm.asyncio import tqdm\n", "from tenacity import retry, stop_after_attempt, wait_exponential\n", "\n", "# from wikiquote_tv.constants import idxurls, timeout, wikiquote_url\n", "wikiquote_url = \"https://en.wikiquote.org\"\n", "\n", "a_through_h = f\"{wikiquote_url}/wiki/List_of_television_shows_(A%E2%80%93H)\"\n", "i_through_p = f\"{wikiquote_url}/wiki/List_of_television_shows_(I%E2%80%93P)\"\n", "q_through_z = f\"{wikiquote_url}/wiki/List_of_television_shows_(Q%E2%80%93Z)\"\n", "\n", "idxurls = [\n", " a_through_h,\n", " i_through_p,\n", " q_through_z,\n", "]\n", "\n", "timeout = 10\n", "\n", "\n", "class Action(BaseModel):\n", " text: str\n", "\n", " def __str__(self):\n", " return self.text\n", "\n", "\n", "class Quote(BaseModel):\n", " speaker: str\n", " text: str\n", "\n", " def __str__(self):\n", " return f\"{self.speaker}: {self.text}\"\n", "\n", "\n", "class Conversation(BaseModel):\n", " quotes: list[Union[Quote, Action]]\n", "\n", " def __str__(self):\n", " return \"\\n\".join(str(quote) for quote in self.quotes)\n", "\n", " def format_example(self) -> dict:\n", " input_text = (\n", " \"\\n\".join(str(quote) for quote in self.quotes[:-1])\n", " + \"\\n\"\n", " + self.quotes[-1].speaker\n", " + \": \"\n", " )\n", " target_text = self.quotes[-1].text\n", " return {\"input_text\": input_text, \"target_text\": target_text}\n", "\n", "\n", "def parse_quote(quote):\n", " try:\n", " speaker = quote.find(\"b\").text\n", " except AttributeError:\n", " return Action(text=quote.text)\n", " text = quote.text.replace(speaker, \"\").strip(\": \")\n", " return Quote(text=text, speaker=speaker)\n", "\n", "\n", "@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))\n", "async def get_shows(session: aiohttp.ClientSession) -> dict[str, str]:\n", " def get_links(soup) -> dict[str, str]:\n", " def _gen():\n", " h2_tags = soup.find_all(\"h2\")\n", "\n", " start = h2_tags[0] # includes existing and requested\n", " end = h2_tags[2] # Notes\n", "\n", " existing = \"\"\n", " for elem in start.next_siblings:\n", " if elem == end:\n", " break\n", " existing += str(elem)\n", " new_soup = BeautifulSoup(existing, \"html.parser\")\n", " for link in new_soup.find_all(\"li\"):\n", " if link.a:\n", " relative_path = link.a[\"href\"].strip(\"/\")\n", " link_url = f\"{wikiquote_url}/{relative_path}\"\n", " try:\n", " name = link.a[\"title\"]\n", " except KeyError:\n", " continue\n", " if name.endswith(\"(page does not exist)\"):\n", " continue\n", " yield name, link_url\n", "\n", " return dict(_gen())\n", "\n", " result = {}\n", " async for url in tqdm(idxurls):\n", " resp = await session.get(url, timeout=timeout)\n", " content = await resp.text()\n", " soup = BeautifulSoup(content)\n", " links = get_links(soup)\n", " result.update(links)\n", " return result\n", "\n", "\n", "def season_links(soup: BeautifulSoup) -> Union[set, None]:\n", " pattern = re.compile(r\"\\(season_\\d+\\)$\")\n", " return {\n", " f\"{wikiquote_url}/{a['href'].strip('/')}\"\n", " for a in soup.find_all(\"a\", href=lambda x: x and pattern.search(x))\n", " } or None\n", "\n", "\n", "def show_season(soup: BeautifulSoup) -> dict[str, str]:\n", " show_season_pat = re.compile(r\"^(?P.*?)(?: \\(season (?P\\d+)\\))?$\")\n", " show_season_text = soup.find(\"h1\").text\n", " show_season_match = show_season_pat.match(show_season_text)\n", " if show_season_match is None:\n", " raise ValueError(\n", " f\"Could not parse show and season from {show_season_text}\",\n", " )\n", " return show_season_match.groupdict()\n", "\n", "\n", "def episode_objects(soup: BeautifulSoup) -> list[tuple[str, str, Conversation]]:\n", " # Assuming `soup` is your BeautifulSoup object\n", " contents = soup.find_all([\"h3\", \"dl\", \"p\", \"hr\"]) # Include 'h3' in the search\n", "\n", " merged_dls = []\n", " temp_content = \"\"\n", " inside_dl = False\n", " current_title = None\n", " next_title = None\n", "\n", " show_name = show_season(soup)[\"show\"]\n", "\n", " for content in contents:\n", " if content.name == \"h3\":\n", " # If inside a
, close it before starting a new section\n", " if inside_dl:\n", " merged_dls.append((current_title, temp_content))\n", " temp_content = \"\"\n", " inside_dl = False\n", "\n", " # Store the next title\n", " next_title = content.get_text()\n", "\n", " elif content.name == \"dl\":\n", " if not inside_dl:\n", " # Start of a new
section, update the current title\n", " current_title = next_title\n", " temp_content = str(content)\n", " inside_dl = True\n", " else:\n", " # Continue the current
section\n", " temp_content += str(content)\n", "\n", " elif content.name == \"p\" and inside_dl:\n", " # Part of a split
section\n", " temp_content += str(content)\n", "\n", " elif content.name == \"hr\":\n", " #
tag encountered, end current
if within one\n", " if inside_dl:\n", " merged_dls.append((current_title, temp_content))\n", " temp_content = \"\"\n", " inside_dl = False\n", "\n", " # Add the last
section if the loop ends while inside a
\n", " if inside_dl:\n", " merged_dls.append((current_title, temp_content))\n", "\n", " editpat = re.compile(r\"\\[edit]$\")\n", "\n", " def _gen():\n", " for title, dl in merged_dls:\n", " if isinstance(title, str):\n", " title = editpat.sub(\"\", title)\n", " dlsoup = BeautifulSoup(dl, \"html.parser\")\n", " conversation = Conversation(\n", " quotes=[parse_quote(quote) for quote in dlsoup.find_all(\"dd\")],\n", " )\n", " yield show_name, title, conversation\n", "\n", " return list(_gen())\n", "\n", "\n", "@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))\n", "async def longurllist(test: bool = False) -> list[tuple[str, str, Conversation]]:\n", " async with aiohttp.ClientSession() as session:\n", "\n", " async def _gen():\n", " shows = await get_shows(session)\n", " show_items = shows.items() if not test else list(shows.items())[:3]\n", " async for show, url in tqdm(show_items):\n", " show_resp = await session.get(url, timeout=timeout)\n", " show_text = await show_resp.text()\n", " show_soup = BeautifulSoup(show_text)\n", " show_season_links = season_links(show_soup)\n", " if show_season_links is None:\n", " for ep_obj in episode_objects(show_soup):\n", " yield ep_obj\n", "\n", " else:\n", " async for season_url in tqdm(show_season_links):\n", " season_resp = await session.get(season_url, timeout=timeout)\n", " season_text = await season_resp.text()\n", " season_soup = BeautifulSoup(season_text)\n", " for ep_obj in episode_objects(season_soup):\n", " yield ep_obj\n", "\n", " return [ep_obj async for ep_obj in _gen()]\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "7df36e4b-0712-4040-907e-17740aa78f20", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import nest_asyncio\n", "\n", "nest_asyncio.apply()" ] }, { "cell_type": "code", "execution_count": 24, "id": "2a35e6ff-ac01-4343-ac48-0dcd4edd843a", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.61it/s]\n", " 0%|▎ | 5/1147 [00:00<03:38, 5.22it/s]\n", " 0%| | 0/6 [00:00\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", "
showepisodeconversation
010 Things I Hate About You (TV series)Pilot [1.01]Bianca: How do I look?\\nKat: Shallow.\\nBianca:...
110 Things I Hate About You (TV series)Pilot [1.01]Kat: What do you want?\\nPatrick: What you mean...
210 Things I Hate About You (TV series)Pilot [1.01]Bianca: [to Kat] You've ruined my chances of b...
310 Things I Hate About You (TV series)Pilot [1.01]Kat: [to Patrick] Why are people scared of you...
410 Things I Hate About You (TV series)Pilot [1.01]Chastity: My neck is sore.\\nKat: That's probab...
\n", "" ], "text/plain": [ " show episode \\\n", "0 10 Things I Hate About You (TV series) Pilot [1.01] \n", "1 10 Things I Hate About You (TV series) Pilot [1.01] \n", "2 10 Things I Hate About You (TV series) Pilot [1.01] \n", "3 10 Things I Hate About You (TV series) Pilot [1.01] \n", "4 10 Things I Hate About You (TV series) Pilot [1.01] \n", "\n", " conversation \n", "0 Bianca: How do I look?\\nKat: Shallow.\\nBianca:... \n", "1 Kat: What do you want?\\nPatrick: What you mean... \n", "2 Bianca: [to Kat] You've ruined my chances of b... \n", "3 Kat: [to Patrick] Why are people scared of you... \n", "4 Chastity: My neck is sore.\\nKat: That's probab... " ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.head()" ] }, { "cell_type": "code", "execution_count": 33, "id": "fc5ad237-db2e-4df8-8f0c-a4351f247792", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Conversation(quotes=[Quote(speaker='Bianca', text='How do I look?'), Quote(speaker='Kat', text='Shallow.'), Quote(speaker='Bianca', text='(happy) Thank you!')])" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df['conversation'][0]" ] }, { "cell_type": "code", "execution_count": 93, "id": "4a40281b-d690-48da-8825-64eba0da66a8", "metadata": {}, "outputs": [], "source": [ "import unicodedata\n", "\n", "def format_example_2(convo: Conversation) -> dict:\n", " input_text = \"\\n\".join(str(quote) for quote in convo.quotes[:-1])\n", " try:\n", " target_text = convo.quotes[-1].text\n", " except IndexError:\n", " print(convo)\n", " return None\n", " try:\n", " return {\n", " k: unicodedata.normalize('NFKD', v).encode('ASCII', 'ignore').decode()\n", " for k, v in {\"input_text\": input_text, \"speaker\": convo.quotes[-1].speaker, \"target_text\": target_text}.items()\n", " }\n", " except AttributeError:\n", " return None" ] }, { "cell_type": "code", "execution_count": 94, "id": "cba32c14-4e87-4475-8f22-61faa74cbaa5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wall time: 128 ms\n" ] } ], "source": [ "%%time\n", "\n", "df = df.assign(turns=df['conversation'].apply(lambda c: len(c.quotes)))" ] }, { "cell_type": "code", "execution_count": 95, "id": "529f3ac5-2960-406f-91b2-84cb1807d2d9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "\n" ] } ], "source": [ "df['tgtdict'] = df['conversation'].apply(format_example_2)" ] }, { "cell_type": "code", "execution_count": 96, "id": "8b35bb30-ebab-4d50-8ac3-fecba5579290", "metadata": {}, "outputs": [], "source": [ "train_df = df.dropna(subset=['tgtdict'])" ] }, { "cell_type": "code", "execution_count": 97, "id": "d0e0909d-3b31-43bb-ac46-3ff261d30864", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(145354, 139823)" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(df), len(train_df)" ] }, { "cell_type": "code", "execution_count": 98, "id": "2c78e569-8338-450e-b52b-9396cf292cbd", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wall time: 23.2 s\n" ] } ], "source": [ "%%time\n", "\n", "train_df = train_df.join(train_df['tgtdict'].apply(pd.Series))" ] }, { "cell_type": "code", "execution_count": 99, "id": "ef00e42c-3bdc-4f9b-9a98-09fc35d86724", "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", "
showepisodeconversationtgtdictturnsinput_textspeakertarget_text
010 Things I Hate About You (TV series)Pilot [1.01]Bianca: How do I look?\\nKat: Shallow.\\nBianca:...{'input_text': 'Bianca: How do I look?\n", "Kat: Sh...3Bianca: How do I look?\\nKat: Shallow.Bianca(happy) Thank you!
110 Things I Hate About You (TV series)Pilot [1.01]Kat: What do you want?\\nPatrick: What you mean...{'input_text': 'Kat: What do you want?\n", "Patrick...6Kat: What do you want?\\nPatrick: What you mean...Patrick[smiling] : Sure they are. That's why I find y...
210 Things I Hate About You (TV series)Pilot [1.01]Bianca: [to Kat] You've ruined my chances of b...{'input_text': 'Bianca: [to Kat] You've ruined...4Bianca: [to Kat] You've ruined my chances of b...KatKim Jong II, the dictator of North Korea!
310 Things I Hate About You (TV series)Pilot [1.01]Kat: [to Patrick] Why are people scared of you...{'input_text': 'Kat: [to Patrick] Why are peop...4Kat: [to Patrick] Why are people scared of you...PatrickSure they are. That's why I find you interesting.
410 Things I Hate About You (TV series)Pilot [1.01]Chastity: My neck is sore.\\nKat: That's probab...{'input_text': 'Chastity: My neck is sore.\n", "Kat...5Chastity: My neck is sore.\\nKat: That's probab...Kat and BiancaDad!
\n", "
" ], "text/plain": [ " show episode \\\n", "0 10 Things I Hate About You (TV series) Pilot [1.01] \n", "1 10 Things I Hate About You (TV series) Pilot [1.01] \n", "2 10 Things I Hate About You (TV series) Pilot [1.01] \n", "3 10 Things I Hate About You (TV series) Pilot [1.01] \n", "4 10 Things I Hate About You (TV series) Pilot [1.01] \n", "\n", " conversation \\\n", "0 Bianca: How do I look?\\nKat: Shallow.\\nBianca:... \n", "1 Kat: What do you want?\\nPatrick: What you mean... \n", "2 Bianca: [to Kat] You've ruined my chances of b... \n", "3 Kat: [to Patrick] Why are people scared of you... \n", "4 Chastity: My neck is sore.\\nKat: That's probab... \n", "\n", " tgtdict turns \\\n", "0 {'input_text': 'Bianca: How do I look?\n", "Kat: Sh... 3 \n", "1 {'input_text': 'Kat: What do you want?\n", "Patrick... 6 \n", "2 {'input_text': 'Bianca: [to Kat] You've ruined... 4 \n", "3 {'input_text': 'Kat: [to Patrick] Why are peop... 4 \n", "4 {'input_text': 'Chastity: My neck is sore.\n", "Kat... 5 \n", "\n", " input_text speaker \\\n", "0 Bianca: How do I look?\\nKat: Shallow. Bianca \n", "1 Kat: What do you want?\\nPatrick: What you mean... Patrick \n", "2 Bianca: [to Kat] You've ruined my chances of b... Kat \n", "3 Kat: [to Patrick] Why are people scared of you... Patrick \n", "4 Chastity: My neck is sore.\\nKat: That's probab... Kat and Bianca \n", "\n", " target_text \n", "0 (happy) Thank you! \n", "1 [smiling] : Sure they are. That's why I find y... \n", "2 Kim Jong II, the dictator of North Korea! \n", "3 Sure they are. That's why I find you interesting. \n", "4 Dad! " ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_df.head()" ] }, { "cell_type": "code", "execution_count": 100, "id": "2519de2e-91a3-413c-9a0a-0705b90cca2a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "139823" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(train_df)" ] }, { "cell_type": "code", "execution_count": 101, "id": "5d9f4f6e-b6a2-422d-9b65-e13fe84a68c1", "metadata": {}, "outputs": [], "source": [ "train_df_dropna = train_df.drop(columns=['conversation', 'tgtdict']).dropna(axis=0, how='any').dropna(axis=1, how='any')" ] }, { "cell_type": "code", "execution_count": 102, "id": "38920915-ac9b-4221-84f5-76e1e780806e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "139823" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(train_df_dropna)" ] }, { "cell_type": "code", "execution_count": 103, "id": "3105ae82-4193-4c05-8101-649252809184", "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", "
showepisodeturnsinput_textspeakertarget_text
010 Things I Hate About You (TV series)Pilot [1.01]3Bianca: How do I look?\\nKat: Shallow.Bianca(happy) Thank you!
110 Things I Hate About You (TV series)Pilot [1.01]6Kat: What do you want?\\nPatrick: What you mean...Patrick[smiling] : Sure they are. That's why I find y...
210 Things I Hate About You (TV series)Pilot [1.01]4Bianca: [to Kat] You've ruined my chances of b...KatKim Jong II, the dictator of North Korea!
310 Things I Hate About You (TV series)Pilot [1.01]4Kat: [to Patrick] Why are people scared of you...PatrickSure they are. That's why I find you interesting.
410 Things I Hate About You (TV series)Pilot [1.01]5Chastity: My neck is sore.\\nKat: That's probab...Kat and BiancaDad!
\n", "
" ], "text/plain": [ " show episode turns \\\n", "0 10 Things I Hate About You (TV series) Pilot [1.01] 3 \n", "1 10 Things I Hate About You (TV series) Pilot [1.01] 6 \n", "2 10 Things I Hate About You (TV series) Pilot [1.01] 4 \n", "3 10 Things I Hate About You (TV series) Pilot [1.01] 4 \n", "4 10 Things I Hate About You (TV series) Pilot [1.01] 5 \n", "\n", " input_text speaker \\\n", "0 Bianca: How do I look?\\nKat: Shallow. Bianca \n", "1 Kat: What do you want?\\nPatrick: What you mean... Patrick \n", "2 Bianca: [to Kat] You've ruined my chances of b... Kat \n", "3 Kat: [to Patrick] Why are people scared of you... Patrick \n", "4 Chastity: My neck is sore.\\nKat: That's probab... Kat and Bianca \n", "\n", " target_text \n", "0 (happy) Thank you! \n", "1 [smiling] : Sure they are. That's why I find y... \n", "2 Kim Jong II, the dictator of North Korea! \n", "3 Sure they are. That's why I find you interesting. \n", "4 Dad! " ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_df_dropna.head()" ] }, { "cell_type": "code", "execution_count": 104, "id": "b38f8372-c7cc-4422-b30a-8fd457bd1c2b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"[smiling] : Sure they are. That's why I find you interesting [he goes away in his motorcycle]\"" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(train_df_dropna.iloc[1]['target_text'])" ] }, { "cell_type": "code", "execution_count": 111, "id": "7d210526-ec54-40aa-9661-906d00fd5462", "metadata": {}, "outputs": [], "source": [ "more_than_one_turn = train_df_dropna.loc[train_df_dropna['turns'] > 1]" ] }, { "cell_type": "code", "execution_count": 114, "id": "20cfd23b-27c1-4853-840b-2266a0ff7422", "metadata": {}, "outputs": [], "source": [ "more_than_one_turn.to_parquet(\"wikiquote_tv.parquet\", index=False)" ] } ], "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.9.16" } }, "nbformat": 4, "nbformat_minor": 5 }