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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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "DEMO_MODE = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Importing necessary libraries:\n",
    "# - os, json, time for file, data and time operations respectively.\n",
    "# - requests for making HTTP requests.\n",
    "# - BeautifulSoup for parsing HTML content.\n",
    "# - Other imports for logging, data manipulation, progress indication, and more.\n",
    "import os\n",
    "import json\n",
    "import time\n",
    "import munch\n",
    "import requests\n",
    "import argparse\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "from datetime import date\n",
    "from loguru import logger\n",
    "from random import randint\n",
    "from bs4 import BeautifulSoup, NavigableString\n",
    "\n",
    "from preprocessing.preprocessing_sub_functions import remove_emojis\n",
    "from topic_crawling import loop_through_posts\n",
    "\n",
    "\n",
    "# This function reads a JSON file named \"website_format.json\".\n",
    "# The file contain a list of user agents.\n",
    "# User agents are strings that browsers send to websites to identify themselves.\n",
    "# This list is likely used to rotate between different user agents when making requests,\n",
    "# making the scraper seem like different browsers and reducing the chances of being blocked.\n",
    "def get_web_component():\n",
    "    with open(\"website_format.json\") as json_file:\n",
    "        website_format = json.load(json_file)\n",
    "    website_format = munch.munchify(website_format)\n",
    "    return website_format.USER_AGENTS\n",
    "\n",
    "\n",
    "# This function fetches a webpage's content.\n",
    "# It randomly selects a user agent from the provided list to make the request.\n",
    "# After fetching, it uses BeautifulSoup to parse the page's HTML content.\n",
    "# def get_web_content(url, USER_AGENTS):\n",
    "#     random_agent = USER_AGENTS[randint(0, len(USER_AGENTS) - 1)]\n",
    "#     headers = {\"User-Agent\": random_agent}\n",
    "#     req = requests.get(url, headers=headers)\n",
    "#     req.encoding = req.apparent_encoding\n",
    "#     soup = BeautifulSoup(req.text, features=\"lxml\")\n",
    "#     return soup\n",
    "from topic_crawling import get_web_content\n",
    "\n",
    "\n",
    "# This function extracts pagination links from a page.\n",
    "# These links point to other pages of content, often seen at the bottom of forums or search results.\n",
    "# The function returns both the individual page links and the \"next\" link,\n",
    "# which points to the next set of results.\n",
    "def get_pages_urls(url, USER_AGENTS):\n",
    "    time.sleep(1)\n",
    "    soup = get_web_content(url, USER_AGENTS)\n",
    "    # Finding the pagination links based on their HTML structure and CSS classes.\n",
    "    first_td = soup.find(\"td\", class_=\"middletext\", id=\"toppages\")\n",
    "    nav_pages_links = first_td.find_all(\"a\", class_=\"navPages\")\n",
    "    href_links = [link[\"href\"] for link in nav_pages_links]\n",
    "    next_50_link = href_links[-3]  # Assuming the third-last link is the \"next\" link.\n",
    "    href_links.insert(0, url)\n",
    "    return href_links, next_50_link\n",
    "\n",
    "\n",
    "# This function extracts individual post URLs from a page.\n",
    "# It's likely targeting a forum or blog structure, where multiple posts or threads are listed on one page.\n",
    "def get_post_urls(url, USER_AGENTS):\n",
    "    time.sleep(1)\n",
    "    soup = get_web_content(url, USER_AGENTS)\n",
    "    # Finding post links based on their HTML structure and CSS classes.\n",
    "    links_elements = soup.select(\"td.windowbg span a\")\n",
    "    links = [link[\"href\"] for link in links_elements]\n",
    "\n",
    "    # # If including rules and announcements posts\n",
    "    # links_elements = soup.select('td.windowbg3 span a')\n",
    "    # links_ = [link['href'] for link in links_elements]\n",
    "    # links.extend(links_)\n",
    "\n",
    "    return links\n",
    "\n",
    "\n",
    "# This function loops through the main page and its paginated versions to collect URLs.\n",
    "# It repeatedly calls 'get_pages_urls' to fetch batches of URLs until the desired number (num_of_pages) is reached.\n",
    "def loop_through_source_url(USER_AGENTS, url, num_of_pages):\n",
    "    pages_urls = []\n",
    "    counter = 0\n",
    "    while len(pages_urls) < num_of_pages:\n",
    "        print(\"loop_through_source_url: \", len(pages_urls))\n",
    "        href_links, next_50_link = get_pages_urls(url, USER_AGENTS)\n",
    "        pages_urls.extend(href_links)\n",
    "        pages_urls = list(dict.fromkeys(pages_urls))  # Remove any duplicate URLs.\n",
    "        url = next_50_link\n",
    "    return pages_urls\n",
    "\n",
    "\n",
    "# This function loops through the provided list of page URLs and extracts post URLs from each of these pages.\n",
    "# It ensures that there are no duplicate post URLs by converting the list into a dictionary and back to a list.\n",
    "# It returns a list of unique post URLs.\n",
    "def loop_through_pages(USER_AGENTS, pages_urls):\n",
    "    post_urls = []\n",
    "    for url in tqdm(pages_urls):\n",
    "        herf_links = get_post_urls(url, USER_AGENTS)\n",
    "        post_urls.extend(herf_links)\n",
    "        post_urls = list(dict.fromkeys(post_urls))\n",
    "        if DEMO_MODE:\n",
    "            break\n",
    "    return post_urls\n",
    "\n",
    "# This function processes a post page. It extracts various details like timestamps, author information, post content, topic, attachments, links, and original HTML information.\n",
    "# The function returns a dictionary containing all this extracted data.\n",
    "def read_subject_page(USER_AGENTS, post_url, df, remove_emoji):\n",
    "    time.sleep(1)\n",
    "    soup = get_web_content(post_url, USER_AGENTS)\n",
    "    form_tag = soup.find(\"form\", id=\"quickModForm\")\n",
    "    table_tag = form_tag.find(\"table\", class_=\"bordercolor\")\n",
    "    td_tag = table_tag.find_all(\"td\", class_=\"windowbg\")\n",
    "    td_tag.extend(table_tag.find_all(\"td\", class_=\"windowbg2\"))\n",
    "\n",
    "    for comment in tqdm(td_tag):\n",
    "        res = extract_useful_content_windowbg(comment, remove_emoji)\n",
    "        if res is not None:\n",
    "            df = pd.concat([df, pd.DataFrame([res])])\n",
    "\n",
    "    return df\n",
    "\n",
    "# This function extracts meaningful content from a given HTML element (`tr_tag`). This tag is likely a row in a table, given its name.\n",
    "# The function checks the presence of specific tags and classes within this row to extract information such as timestamps, author, post content, topic, attachments, and links.\n",
    "# The extracted data is returned as a dictionary.\n",
    "def extract_useful_content_windowbg(tr_tag, remove_emoji=True):\n",
    "    \"\"\"\n",
    "    Timestamp of the post (ex: September 11, 2023, 07:49:45 AM; but if you want just 11/09/2023 is enough)\n",
    "    Author of the post (ex: SupermanBitcoin)\n",
    "    The post itself\n",
    "\n",
    "    The topic where the post was posted (ex: [INFO - DISCUSSION] Security Budget Problem) eg.  Whats your thoughts: Next-Gen Bitcoin Mining Machine With 1X Efficiency Rating.\n",
    "    Number of characters in the post --> so this is an integer\n",
    "    Does the post contain at least one attachment (image, video etc.) --> if yes put '1' in the column, if no, just put '0'\n",
    "    Does the post contain at least one link --> if yes put '1' in the column, if no, just put '0'\n",
    "    \"\"\"\n",
    "    headerandpost = tr_tag.find(\"td\", class_=\"td_headerandpost\")\n",
    "    if not headerandpost:\n",
    "        return None\n",
    "\n",
    "    timestamp = headerandpost.find(\"div\", class_=\"smalltext\").get_text()\n",
    "    timestamps = timestamp.split(\"Last edit: \")\n",
    "    timestamp = timestamps[0].strip()\n",
    "    last_edit = None\n",
    "    if len(timestamps) > 1:\n",
    "        if 'Today ' in timestamps[1]:\n",
    "            last_edit = date.today().strftime(\"%B %d, %Y\")+', '+timestamps[1].split('by')[0].split(\"Today at\")[1].strip()\n",
    "        last_edit = timestamps[1].split('by')[0].strip()\n",
    "\n",
    "    poster_info_tag = tr_tag.find('td', class_='poster_info')\n",
    "    anchor_tag = poster_info_tag.find('a')\n",
    "    author = \"Anonymous\" if anchor_tag is None else anchor_tag.get_text()\n",
    "\n",
    "    link = 0\n",
    "\n",
    "    post_ = tr_tag.find('div', class_='post')\n",
    "    texts = []\n",
    "    for child in post_.children:\n",
    "        if isinstance(child, NavigableString):\n",
    "            texts.append(child.strip())\n",
    "        elif child.has_attr('class') and 'ul' in child['class']:\n",
    "            link = 1\n",
    "            texts.append(child.get_text(strip=True))\n",
    "    post = ' '.join(texts)\n",
    "\n",
    "    topic = headerandpost.find('div', class_='subject').get_text()\n",
    "\n",
    "    image = headerandpost.find('div', class_='post').find_all('img')\n",
    "    if remove_emoji:\n",
    "        image = remove_emojis(image)\n",
    "    image_ = min(len(image), 1)\n",
    "    \n",
    "    video = headerandpost.find('div', class_='post').find('video')\n",
    "    video_ = 0 if video is None else 1\n",
    "    attachment = max(image_, video_)\n",
    "\n",
    "    original_info = headerandpost\n",
    "\n",
    "    return {\n",
    "        \"timestamp\": timestamp,\n",
    "        \"last_edit\": last_edit,\n",
    "        \"author\": author.strip(),\n",
    "        \"post\": post.strip(),\n",
    "        \"topic\": topic.strip(),\n",
    "        \"attachment\": attachment,\n",
    "        \"link\": link,\n",
    "        \"original_info\": original_info,\n",
    "    }\n",
    "\n",
    "\n",
    "# A utility function to save a list (e.g., URLs) to a text file.\n",
    "# Each item in the list gets its own line in the file.\n",
    "def save_page_file(data, file_name):\n",
    "    with open(file_name, \"w\") as filehandle:\n",
    "        for listitem in data:\n",
    "            filehandle.write(\"%s\\n\" % listitem)\n",
    "\n",
    "def get_post_max_page(url, USER_AGENTS):\n",
    "    soup = get_web_content(url, USER_AGENTS)\n",
    "    # Finding the pagination links based on their HTML structure and CSS classes.\n",
    "    first_td = soup.find('td', class_='middletext')\n",
    "    nav_pages_links = first_td.find_all('a', class_='navPages')\n",
    "\n",
    "    href_links = [int(link.text) if link.text.isdigit() else 0 for link in nav_pages_links]\n",
    "    if len(href_links) == 0:\n",
    "        # print('No pagination links found: ', url)\n",
    "        return 1\n",
    "    m = max(href_links)\n",
    "    # we can't use more than 10 pages\n",
    "    m = m if m < 10 else 10\n",
    "    return m\n",
    "\n",
    "\n",
    "# def parse_args():\n",
    "#     parser = argparse.ArgumentParser()\n",
    "#     parser.add_argument(\"url\", help=\"url for the extraction\")\n",
    "#     parser.add_argument(\"--update\", help=\"extract updated data\", action=\"store_true\")\n",
    "#     parser.add_argument(\"--board\", help=\"board name\")\n",
    "#     parser.add_argument(\"--num_of_pages\", '-pages', help=\"number of pages to extract\", type=int)\n",
    "#     parser.add_argument(\"--num_of_posts_start\", '-posts', help=\"the number of posts start to extract\", type=int, default=0)\n",
    "\n",
    "#     parser.add_argument(\"remove_emoji\", help=\"remove emoji from the post\", action=\"store_true\")\n",
    "#     return vars(parser.parse_args())\n",
    "\n",
    "# \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "mining_section = True\n",
    "if mining_section:\n",
    "    url = \"https://bitcointalk.org/index.php?board=14.0\"\n",
    "else:\n",
    "    url = \"https://bitcointalk.org/index.php?board=1.0\"\n",
    "update = False\n",
    "\n",
    "if DEMO_MODE:\n",
    "    board = \"Demo\"\n",
    "    num_of_pages = 1\n",
    "    num_of_posts_start = 0\n",
    "else:\n",
    "    board = \"Bitcoin\"\n",
    "    num_of_pages = 1528\n",
    "    num_of_posts_start = 248\n",
    "\n",
    "\n",
    "\n",
    "remove_emoji = True\n",
    "\n",
    "USER_AGENTS = get_web_component()\n",
    "# Ensuring the data directory exists.\n",
    "os.makedirs(f\"data/{board}/\", exist_ok=True)\n",
    "pages_file_path = f\"data/{board}/pages_urls.txt\"\n",
    "post_file_path = f\"data/{board}/post_urls.txt\"\n",
    "# If the user chose to update the data, existing files are deleted to make way for new data.\n",
    "if update:\n",
    "    if os.path.exists(pages_file_path):\n",
    "        os.remove(pages_file_path)\n",
    "    if os.path.exists(post_file_path):\n",
    "        os.remove(post_file_path)\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loop_through_source_url:  0\n"
     ]
    }
   ],
   "source": [
    "# If the pages file doesn't exist, the script collects page URLs.\n",
    "if not os.path.exists(pages_file_path):\n",
    "    pages_urls = loop_through_source_url(USER_AGENTS, url, num_of_pages)\n",
    "    save_page_file(pages_urls, pages_file_path)\n",
    "# Reading the existing page URLs from the file.\n",
    "with open(pages_file_path, \"r\") as filehandle:\n",
    "    pages_urls = [\n",
    "        current_place.rstrip() for current_place in filehandle.readlines()\n",
    "    ]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|          | 0/52 [00:01<?, ?it/s]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# If the posts file doesn't exist, the script collects post URLs.\n",
    "if not os.path.exists(post_file_path):\n",
    "    post_urls = loop_through_pages(USER_AGENTS, pages_urls)\n",
    "    save_page_file(post_urls, post_file_path)\n",
    "# Reading the existing post URLs from the file.\n",
    "with open(post_file_path, \"r\") as filehandle:\n",
    "    post_urls = [current_place.rstrip() for current_place in filehandle.readlines()]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # for post_url in [\"https://bitcointalk.org/index.php?topic=1306983.0\"]:\n",
    "# for post_url in [\"https://bitcointalk.org/index.php?topic=5489570.0\"]:\n",
    "#     time.sleep(0.8)\n",
    "#     num_of_post_pages = get_post_max_page(post_url, USER_AGENTS)\n",
    "#     loop_through_posts(USER_AGENTS, post_url, board, num_of_post_pages, remove_emoji)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 39/39 [01:02<00:00,  1.60s/it]\n"
     ]
    }
   ],
   "source": [
    "post_urls_to_process = []\n",
    "for post_url in post_urls:\n",
    "    topic_id = post_url.split('topic=')[1]\n",
    "    if os.path.exists(f'data/{board}/data_{topic_id}.csv'):\n",
    "        # print(f'data/{board}/data_{topic_id}.csv already exists')\n",
    "        continue\n",
    "    post_urls_to_process.append(post_url)\n",
    "\n",
    "\n",
    "# for (i,post_url) in enumerate(post_urls_to_process):\n",
    "for post_url in tqdm(post_urls_to_process):\n",
    "    num_of_post_pages = get_post_max_page(post_url, USER_AGENTS)\n",
    "    loop_through_posts(USER_AGENTS, post_url, board, num_of_post_pages, remove_emoji)\n",
    "    # print(f'{i+1}/{len(post_urls_to_process)} urls done')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import time\n",
    "# import winsound\n",
    "# from tqdm import tqdm\n",
    "# winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py310",
   "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.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}