Aghiless commited on
Commit
730228c
·
verified ·
1 Parent(s): ef6f28d

Upload 3 files

Browse files
Files changed (3) hide show
  1. datacreation.ipynb +1251 -0
  2. pythonanalysis.ipynb +0 -0
  3. ranalysis.ipynb +529 -0
datacreation.ipynb ADDED
@@ -0,0 +1,1251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "4ba6aba8"
7
+ },
8
+ "source": [
9
+ "# 🤖 **Data Collection, Creation, Storage, and Processing**\n"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {
15
+ "id": "jpASMyIQMaAq"
16
+ },
17
+ "source": [
18
+ "## **1.** 📦 Install required packages"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": 2,
24
+ "metadata": {
25
+ "colab": {
26
+ "base_uri": "https://localhost:8080/"
27
+ },
28
+ "id": "f48c8f8c",
29
+ "outputId": "58a1c753-5c10-4635-8a1b-df629b67e2ac"
30
+ },
31
+ "outputs": [
32
+ {
33
+ "output_type": "stream",
34
+ "name": "stdout",
35
+ "text": [
36
+ "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
37
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
38
+ "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
39
+ "Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
40
+ "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
41
+ "Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
42
+ "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
43
+ "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
44
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
45
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
46
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
47
+ "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
48
+ "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
49
+ "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.61.1)\n",
50
+ "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.4.9)\n",
51
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
52
+ "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
53
+ "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
54
+ "Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
55
+ "Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
56
+ "Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
57
+ "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
58
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
59
+ "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
60
+ ]
61
+ }
62
+ ],
63
+ "source": [
64
+ "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "markdown",
69
+ "metadata": {
70
+ "id": "lquNYCbfL9IM"
71
+ },
72
+ "source": [
73
+ "## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "metadata": {
79
+ "id": "0IWuNpxxYDJF"
80
+ },
81
+ "source": [
82
+ "### *a. Initial setup*\n",
83
+ "Define the base url of the website you will scrape as well as how and what you will scrape"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": 3,
89
+ "metadata": {
90
+ "id": "91d52125"
91
+ },
92
+ "outputs": [],
93
+ "source": [
94
+ "import requests\n",
95
+ "from bs4 import BeautifulSoup\n",
96
+ "import pandas as pd\n",
97
+ "import time\n",
98
+ "\n",
99
+ "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
100
+ "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
101
+ "\n",
102
+ "titles, prices, ratings = [], [], []"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "markdown",
107
+ "metadata": {
108
+ "id": "oCdTsin2Yfp3"
109
+ },
110
+ "source": [
111
+ "### *b. Fill titles, prices, and ratings from the web pages*"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": 4,
117
+ "metadata": {
118
+ "id": "xqO5Y3dnYhxt"
119
+ },
120
+ "outputs": [],
121
+ "source": [
122
+ "# Loop through all 50 pages\n",
123
+ "for page in range(1, 51):\n",
124
+ " url = base_url.format(page)\n",
125
+ " response = requests.get(url, headers=headers)\n",
126
+ " soup = BeautifulSoup(response.content, \"html.parser\")\n",
127
+ " books = soup.find_all(\"article\", class_=\"product_pod\")\n",
128
+ "\n",
129
+ " for book in books:\n",
130
+ " titles.append(book.h3.a[\"title\"])\n",
131
+ " prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
132
+ " ratings.append(book.p.get(\"class\")[1])\n",
133
+ "\n",
134
+ " time.sleep(0.5) # polite scraping delay"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "markdown",
139
+ "metadata": {
140
+ "id": "T0TOeRC4Yrnn"
141
+ },
142
+ "source": [
143
+ "### *c. ✋🏻🛑⛔️ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": 5,
149
+ "metadata": {
150
+ "id": "l5FkkNhUYTHh"
151
+ },
152
+ "outputs": [],
153
+ "source": [
154
+ "df_books= pd.DataFrame({'title': titles, 'price': prices, 'rating': ratings})"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "markdown",
159
+ "metadata": {
160
+ "id": "duI5dv3CZYvF"
161
+ },
162
+ "source": [
163
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": 6,
169
+ "metadata": {
170
+ "id": "lC1U_YHtZifh"
171
+ },
172
+ "outputs": [],
173
+ "source": [
174
+ "# 💾 Save to CSV\n",
175
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
176
+ "\n",
177
+ "# 💾 Or save to Excel\n",
178
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
179
+ ]
180
+ },
181
+ {
182
+ "cell_type": "markdown",
183
+ "metadata": {
184
+ "id": "qMjRKMBQZlJi"
185
+ },
186
+ "source": [
187
+ "### *e. ✋🏻🛑⛔️ View first fiew lines*"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": 7,
193
+ "metadata": {
194
+ "colab": {
195
+ "base_uri": "https://localhost:8080/",
196
+ "height": 204
197
+ },
198
+ "id": "O_wIvTxYZqCK",
199
+ "outputId": "3d22c37a-d5b2-4818-f6d8-3005af8b5387"
200
+ },
201
+ "outputs": [
202
+ {
203
+ "output_type": "execute_result",
204
+ "data": {
205
+ "text/plain": [
206
+ " title price rating\n",
207
+ "0 A Light in the Attic 51.77 Three\n",
208
+ "1 Tipping the Velvet 53.74 One\n",
209
+ "2 Soumission 50.10 One\n",
210
+ "3 Sharp Objects 47.82 Four\n",
211
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
212
+ ],
213
+ "text/html": [
214
+ "\n",
215
+ " <div id=\"df-c3eefdf4-9015-402e-819b-c1141e3e740a\" class=\"colab-df-container\">\n",
216
+ " <div>\n",
217
+ "<style scoped>\n",
218
+ " .dataframe tbody tr th:only-of-type {\n",
219
+ " vertical-align: middle;\n",
220
+ " }\n",
221
+ "\n",
222
+ " .dataframe tbody tr th {\n",
223
+ " vertical-align: top;\n",
224
+ " }\n",
225
+ "\n",
226
+ " .dataframe thead th {\n",
227
+ " text-align: right;\n",
228
+ " }\n",
229
+ "</style>\n",
230
+ "<table border=\"1\" class=\"dataframe\">\n",
231
+ " <thead>\n",
232
+ " <tr style=\"text-align: right;\">\n",
233
+ " <th></th>\n",
234
+ " <th>title</th>\n",
235
+ " <th>price</th>\n",
236
+ " <th>rating</th>\n",
237
+ " </tr>\n",
238
+ " </thead>\n",
239
+ " <tbody>\n",
240
+ " <tr>\n",
241
+ " <th>0</th>\n",
242
+ " <td>A Light in the Attic</td>\n",
243
+ " <td>51.77</td>\n",
244
+ " <td>Three</td>\n",
245
+ " </tr>\n",
246
+ " <tr>\n",
247
+ " <th>1</th>\n",
248
+ " <td>Tipping the Velvet</td>\n",
249
+ " <td>53.74</td>\n",
250
+ " <td>One</td>\n",
251
+ " </tr>\n",
252
+ " <tr>\n",
253
+ " <th>2</th>\n",
254
+ " <td>Soumission</td>\n",
255
+ " <td>50.10</td>\n",
256
+ " <td>One</td>\n",
257
+ " </tr>\n",
258
+ " <tr>\n",
259
+ " <th>3</th>\n",
260
+ " <td>Sharp Objects</td>\n",
261
+ " <td>47.82</td>\n",
262
+ " <td>Four</td>\n",
263
+ " </tr>\n",
264
+ " <tr>\n",
265
+ " <th>4</th>\n",
266
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
267
+ " <td>54.23</td>\n",
268
+ " <td>Five</td>\n",
269
+ " </tr>\n",
270
+ " </tbody>\n",
271
+ "</table>\n",
272
+ "</div>\n",
273
+ " <div class=\"colab-df-buttons\">\n",
274
+ "\n",
275
+ " <div class=\"colab-df-container\">\n",
276
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-c3eefdf4-9015-402e-819b-c1141e3e740a')\"\n",
277
+ " title=\"Convert this dataframe to an interactive table.\"\n",
278
+ " style=\"display:none;\">\n",
279
+ "\n",
280
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
281
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
282
+ " </svg>\n",
283
+ " </button>\n",
284
+ "\n",
285
+ " <style>\n",
286
+ " .colab-df-container {\n",
287
+ " display:flex;\n",
288
+ " gap: 12px;\n",
289
+ " }\n",
290
+ "\n",
291
+ " .colab-df-convert {\n",
292
+ " background-color: #E8F0FE;\n",
293
+ " border: none;\n",
294
+ " border-radius: 50%;\n",
295
+ " cursor: pointer;\n",
296
+ " display: none;\n",
297
+ " fill: #1967D2;\n",
298
+ " height: 32px;\n",
299
+ " padding: 0 0 0 0;\n",
300
+ " width: 32px;\n",
301
+ " }\n",
302
+ "\n",
303
+ " .colab-df-convert:hover {\n",
304
+ " background-color: #E2EBFA;\n",
305
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
306
+ " fill: #174EA6;\n",
307
+ " }\n",
308
+ "\n",
309
+ " .colab-df-buttons div {\n",
310
+ " margin-bottom: 4px;\n",
311
+ " }\n",
312
+ "\n",
313
+ " [theme=dark] .colab-df-convert {\n",
314
+ " background-color: #3B4455;\n",
315
+ " fill: #D2E3FC;\n",
316
+ " }\n",
317
+ "\n",
318
+ " [theme=dark] .colab-df-convert:hover {\n",
319
+ " background-color: #434B5C;\n",
320
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
321
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
322
+ " fill: #FFFFFF;\n",
323
+ " }\n",
324
+ " </style>\n",
325
+ "\n",
326
+ " <script>\n",
327
+ " const buttonEl =\n",
328
+ " document.querySelector('#df-c3eefdf4-9015-402e-819b-c1141e3e740a button.colab-df-convert');\n",
329
+ " buttonEl.style.display =\n",
330
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
331
+ "\n",
332
+ " async function convertToInteractive(key) {\n",
333
+ " const element = document.querySelector('#df-c3eefdf4-9015-402e-819b-c1141e3e740a');\n",
334
+ " const dataTable =\n",
335
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
336
+ " [key], {});\n",
337
+ " if (!dataTable) return;\n",
338
+ "\n",
339
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
340
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
341
+ " + ' to learn more about interactive tables.';\n",
342
+ " element.innerHTML = '';\n",
343
+ " dataTable['output_type'] = 'display_data';\n",
344
+ " await google.colab.output.renderOutput(dataTable, element);\n",
345
+ " const docLink = document.createElement('div');\n",
346
+ " docLink.innerHTML = docLinkHtml;\n",
347
+ " element.appendChild(docLink);\n",
348
+ " }\n",
349
+ " </script>\n",
350
+ " </div>\n",
351
+ "\n",
352
+ "\n",
353
+ " </div>\n",
354
+ " </div>\n"
355
+ ],
356
+ "application/vnd.google.colaboratory.intrinsic+json": {
357
+ "type": "dataframe",
358
+ "variable_name": "df_books",
359
+ "summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
360
+ }
361
+ },
362
+ "metadata": {},
363
+ "execution_count": 7
364
+ }
365
+ ],
366
+ "source": [
367
+ "df_books.head()"
368
+ ]
369
+ },
370
+ {
371
+ "cell_type": "markdown",
372
+ "metadata": {
373
+ "id": "p-1Pr2szaqLk"
374
+ },
375
+ "source": [
376
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
377
+ ]
378
+ },
379
+ {
380
+ "cell_type": "markdown",
381
+ "metadata": {
382
+ "id": "SIaJUGIpaH4V"
383
+ },
384
+ "source": [
385
+ "### *a. Initial setup*"
386
+ ]
387
+ },
388
+ {
389
+ "cell_type": "code",
390
+ "execution_count": 11,
391
+ "metadata": {
392
+ "id": "-gPXGcRPuV_9"
393
+ },
394
+ "outputs": [],
395
+ "source": [
396
+ "import numpy as np\n",
397
+ "import random\n",
398
+ "from datetime import datetime\n",
399
+ "import warnings\n",
400
+ "\n",
401
+ "warnings.filterwarnings(\"ignore\")\n",
402
+ "random.seed(2025)\n",
403
+ "np.random.seed(2025)"
404
+ ]
405
+ },
406
+ {
407
+ "cell_type": "markdown",
408
+ "metadata": {
409
+ "id": "pY4yCoIuaQqp"
410
+ },
411
+ "source": [
412
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "execution_count": 14,
418
+ "metadata": {
419
+ "id": "mnd5hdAbaNjz"
420
+ },
421
+ "outputs": [],
422
+ "source": [
423
+ "def generate_popularity_score(rating):\n",
424
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
425
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
426
+ " return int(np.clip(base + trend_factor, 1, 5))"
427
+ ]
428
+ },
429
+ {
430
+ "cell_type": "markdown",
431
+ "metadata": {
432
+ "id": "n4-TaNTFgPak"
433
+ },
434
+ "source": [
435
+ "### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "execution_count": 16,
441
+ "metadata": {
442
+ "id": "V-G3OCUCgR07"
443
+ },
444
+ "outputs": [],
445
+ "source": [
446
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)\n",
447
+ "\n"
448
+ ]
449
+ },
450
+ {
451
+ "cell_type": "markdown",
452
+ "metadata": {
453
+ "id": "HnngRNTgacYt"
454
+ },
455
+ "source": [
456
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "code",
461
+ "execution_count": 17,
462
+ "metadata": {
463
+ "id": "kUtWmr8maZLZ"
464
+ },
465
+ "outputs": [],
466
+ "source": [
467
+ "def get_sentiment(popularity_score):\n",
468
+ " if popularity_score <= 2:\n",
469
+ " return \"negative\"\n",
470
+ " elif popularity_score == 3:\n",
471
+ " return \"neutral\"\n",
472
+ " else:\n",
473
+ " return \"positive\""
474
+ ]
475
+ },
476
+ {
477
+ "cell_type": "markdown",
478
+ "metadata": {
479
+ "id": "HF9F9HIzgT7Z"
480
+ },
481
+ "source": [
482
+ "### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
483
+ ]
484
+ },
485
+ {
486
+ "cell_type": "code",
487
+ "execution_count": 18,
488
+ "metadata": {
489
+ "id": "tafQj8_7gYCG"
490
+ },
491
+ "outputs": [],
492
+ "source": [
493
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)"
494
+ ]
495
+ },
496
+ {
497
+ "cell_type": "markdown",
498
+ "metadata": {
499
+ "id": "T8AdKkmASq9a"
500
+ },
501
+ "source": [
502
+ "## **4.** 📈 Generate synthetic book sales data of 18 months"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "markdown",
507
+ "metadata": {
508
+ "id": "OhXbdGD5fH0c"
509
+ },
510
+ "source": [
511
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
512
+ ]
513
+ },
514
+ {
515
+ "cell_type": "code",
516
+ "execution_count": 19,
517
+ "metadata": {
518
+ "id": "qkVhYPXGbgEn"
519
+ },
520
+ "outputs": [],
521
+ "source": [
522
+ "def generate_sales_profile(sentiment):\n",
523
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
524
+ "\n",
525
+ " if sentiment == \"positive\":\n",
526
+ " base = random.randint(200, 300)\n",
527
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
528
+ " elif sentiment == \"negative\":\n",
529
+ " base = random.randint(20, 80)\n",
530
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
531
+ " else: # neutral\n",
532
+ " base = random.randint(80, 160)\n",
533
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
534
+ "\n",
535
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
536
+ " noise = np.random.normal(0, 5, len(months))\n",
537
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
538
+ "\n",
539
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
540
+ ]
541
+ },
542
+ {
543
+ "cell_type": "markdown",
544
+ "metadata": {
545
+ "id": "L2ak1HlcgoTe"
546
+ },
547
+ "source": [
548
+ "### *b. Run the function as part of building sales_data*"
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "code",
553
+ "execution_count": 20,
554
+ "metadata": {
555
+ "id": "SlJ24AUafoDB"
556
+ },
557
+ "outputs": [],
558
+ "source": [
559
+ "sales_data = []\n",
560
+ "for _, row in df_books.iterrows():\n",
561
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
562
+ " for month, units in records:\n",
563
+ " sales_data.append({\n",
564
+ " \"title\": row[\"title\"],\n",
565
+ " \"month\": month,\n",
566
+ " \"units_sold\": units,\n",
567
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
568
+ " })"
569
+ ]
570
+ },
571
+ {
572
+ "cell_type": "markdown",
573
+ "metadata": {
574
+ "id": "4IXZKcCSgxnq"
575
+ },
576
+ "source": [
577
+ "### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*"
578
+ ]
579
+ },
580
+ {
581
+ "cell_type": "code",
582
+ "execution_count": 21,
583
+ "metadata": {
584
+ "id": "wcN6gtiZg-ws"
585
+ },
586
+ "outputs": [],
587
+ "source": [
588
+ "df_sales= pd.DataFrame(sales_data)"
589
+ ]
590
+ },
591
+ {
592
+ "cell_type": "markdown",
593
+ "metadata": {
594
+ "id": "EhIjz9WohAmZ"
595
+ },
596
+ "source": [
597
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
598
+ ]
599
+ },
600
+ {
601
+ "cell_type": "code",
602
+ "execution_count": 22,
603
+ "metadata": {
604
+ "colab": {
605
+ "base_uri": "https://localhost:8080/"
606
+ },
607
+ "id": "MzbZvLcAhGaH",
608
+ "outputId": "18f70c1e-9370-43ce-eac8-2e7071894aac"
609
+ },
610
+ "outputs": [
611
+ {
612
+ "output_type": "stream",
613
+ "name": "stdout",
614
+ "text": [
615
+ " title month units_sold sentiment_label\n",
616
+ "0 A Light in the Attic 2024-08 100 neutral\n",
617
+ "1 A Light in the Attic 2024-09 109 neutral\n",
618
+ "2 A Light in the Attic 2024-10 102 neutral\n",
619
+ "3 A Light in the Attic 2024-11 107 neutral\n",
620
+ "4 A Light in the Attic 2024-12 108 neutral\n"
621
+ ]
622
+ }
623
+ ],
624
+ "source": [
625
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
626
+ "\n",
627
+ "print(df_sales.head())"
628
+ ]
629
+ },
630
+ {
631
+ "cell_type": "markdown",
632
+ "metadata": {
633
+ "id": "7g9gqBgQMtJn"
634
+ },
635
+ "source": [
636
+ "## **5.** 🎯 Generate synthetic customer reviews"
637
+ ]
638
+ },
639
+ {
640
+ "cell_type": "markdown",
641
+ "metadata": {
642
+ "id": "Gi4y9M9KuDWx"
643
+ },
644
+ "source": [
645
+ "### *a. ✋🏻🛑⛔️ Ask ChatGPT to create a list of 50 distinct generic book review texts for the sentiment labels \"positive\", \"neutral\", and \"negative\" called synthetic_reviews_by_sentiment*"
646
+ ]
647
+ },
648
+ {
649
+ "cell_type": "code",
650
+ "execution_count": 23,
651
+ "metadata": {
652
+ "id": "b3cd2a50"
653
+ },
654
+ "outputs": [],
655
+ "source": [
656
+ "synthetic_reviews_by_sentiment = {\n",
657
+ " \"positive\": [\n",
658
+ " \"An absolutely captivating read from start to finish.\",\n",
659
+ " \"I couldn’t put this book down.\",\n",
660
+ " \"A beautifully written and deeply moving story.\",\n",
661
+ " \"The characters felt incredibly real and relatable.\",\n",
662
+ " \"One of the best books I’ve read this year.\",\n",
663
+ " \"A powerful and inspiring narrative.\",\n",
664
+ " \"The plot twists kept me hooked throughout.\",\n",
665
+ " \"Exceptionally well-crafted and engaging.\",\n",
666
+ " \"A masterpiece of storytelling.\",\n",
667
+ " \"The writing style was elegant and immersive.\",\n",
668
+ " \"I loved every chapter of this book.\",\n",
669
+ " \"An unforgettable reading experience.\",\n",
670
+ " \"The pacing was perfect and exciting.\",\n",
671
+ " \"A heartwarming and uplifting story.\",\n",
672
+ " \"Rich character development and strong themes.\",\n",
673
+ " \"Truly a remarkable novel.\",\n",
674
+ " \"This book exceeded my expectations.\",\n",
675
+ " \"A compelling and thoughtful story.\",\n",
676
+ " \"The dialogue felt authentic and natural.\",\n",
677
+ " \"A brilliant and imaginative tale.\",\n",
678
+ " \"I highly recommend this book.\",\n",
679
+ " \"An emotional and satisfying journey.\",\n",
680
+ " \"The ending was incredibly satisfying.\",\n",
681
+ " \"A fresh and original perspective.\",\n",
682
+ " \"An engaging and memorable story.\",\n",
683
+ " \"The author’s voice was strong and confident.\",\n",
684
+ " \"A beautifully structured narrative.\",\n",
685
+ " \"The world-building was impressive.\",\n",
686
+ " \"A delightful and entertaining read.\",\n",
687
+ " \"This story stayed with me long after finishing.\",\n",
688
+ " \"An outstanding contribution to the genre.\",\n",
689
+ " \"The themes were handled with care and depth.\",\n",
690
+ " \"A wonderfully immersive experience.\",\n",
691
+ " \"The writing was both poetic and clear.\",\n",
692
+ " \"A thought-provoking and rewarding read.\",\n",
693
+ " \"The story was gripping and dynamic.\",\n",
694
+ " \"A charming and well-paced novel.\",\n",
695
+ " \"The characters evolved beautifully.\",\n",
696
+ " \"An emotionally resonant book.\",\n",
697
+ " \"A captivating and intelligent story.\",\n",
698
+ " \"The plot was cleverly constructed.\",\n",
699
+ " \"An inspiring and meaningful narrative.\",\n",
700
+ " \"A truly enjoyable book.\",\n",
701
+ " \"The suspense was expertly maintained.\",\n",
702
+ " \"A compelling mix of drama and insight.\",\n",
703
+ " \"The storytelling was vivid and engaging.\",\n",
704
+ " \"A memorable and touching novel.\",\n",
705
+ " \"The author delivered a fantastic story.\",\n",
706
+ " \"An excellent and satisfying read.\",\n",
707
+ " \"I would gladly read this again.\"\n",
708
+ " ],\n",
709
+ "\n",
710
+ " \"neutral\": [\n",
711
+ " \"The book was okay overall.\",\n",
712
+ " \"It was an average reading experience.\",\n",
713
+ " \"Some parts were interesting, others less so.\",\n",
714
+ " \"The story was fine but not exceptional.\",\n",
715
+ " \"A fairly standard plot.\",\n",
716
+ " \"The characters were decent but not memorable.\",\n",
717
+ " \"It had its moments but nothing groundbreaking.\",\n",
718
+ " \"An ordinary book with predictable elements.\",\n",
719
+ " \"The writing style was straightforward.\",\n",
720
+ " \"It was neither great nor terrible.\",\n",
721
+ " \"The pacing was somewhat uneven.\",\n",
722
+ " \"A moderate and balanced read.\",\n",
723
+ " \"The themes were presented clearly.\",\n",
724
+ " \"The book met my expectations.\",\n",
725
+ " \"It was a reasonable way to spend time.\",\n",
726
+ " \"The storyline was simple and easy to follow.\",\n",
727
+ " \"Some chapters were stronger than others.\",\n",
728
+ " \"An acceptable but unremarkable novel.\",\n",
729
+ " \"The ending was satisfactory.\",\n",
730
+ " \"The characters served their purpose.\",\n",
731
+ " \"The narrative felt conventional.\",\n",
732
+ " \"It was a steady but calm story.\",\n",
733
+ " \"The dialogue was functional.\",\n",
734
+ " \"The plot moved at a steady pace.\",\n",
735
+ " \"An average entry in its genre.\",\n",
736
+ " \"Nothing particularly stood out.\",\n",
737
+ " \"It was readable but not thrilling.\",\n",
738
+ " \"The story had both strengths and weaknesses.\",\n",
739
+ " \"A mildly engaging experience.\",\n",
740
+ " \"The setting was described adequately.\",\n",
741
+ " \"The writing was clear and simple.\",\n",
742
+ " \"It delivered what it promised.\",\n",
743
+ " \"The book was competently written.\",\n",
744
+ " \"It felt somewhat familiar.\",\n",
745
+ " \"The structure was conventional.\",\n",
746
+ " \"The tone remained consistent throughout.\",\n",
747
+ " \"It was fairly predictable.\",\n",
748
+ " \"The story was easy to follow.\",\n",
749
+ " \"An overall balanced book.\",\n",
750
+ " \"The ideas were presented plainly.\",\n",
751
+ " \"A neutral reading experience.\",\n",
752
+ " \"It didn’t evoke strong emotions.\",\n",
753
+ " \"The plot resolution was acceptable.\",\n",
754
+ " \"The themes were explored briefly.\",\n",
755
+ " \"The characters were average.\",\n",
756
+ " \"It was neither disappointing nor impressive.\",\n",
757
+ " \"The book maintained a steady rhythm.\",\n",
758
+ " \"An uncomplicated narrative.\",\n",
759
+ " \"A straightforward reading experience.\",\n",
760
+ " \"It was just fine.\"\n",
761
+ " ],\n",
762
+ "\n",
763
+ " \"negative\": [\n",
764
+ " \"I struggled to finish this book.\",\n",
765
+ " \"The story felt dull and uninspired.\",\n",
766
+ " \"The characters were flat and unconvincing.\",\n",
767
+ " \"The pacing was painfully slow.\",\n",
768
+ " \"I found the plot confusing and weak.\",\n",
769
+ " \"The writing style was difficult to enjoy.\",\n",
770
+ " \"This book did not meet my expectations.\",\n",
771
+ " \"The ending was disappointing.\",\n",
772
+ " \"It lacked depth and originality.\",\n",
773
+ " \"The dialogue felt forced.\",\n",
774
+ " \"I lost interest halfway through.\",\n",
775
+ " \"The narrative felt disorganized.\",\n",
776
+ " \"The themes were poorly developed.\",\n",
777
+ " \"The story dragged unnecessarily.\",\n",
778
+ " \"I couldn’t connect with the characters.\",\n",
779
+ " \"The plot twists felt unrealistic.\",\n",
780
+ " \"The book was hard to follow.\",\n",
781
+ " \"It felt repetitive and predictable.\",\n",
782
+ " \"The writing lacked clarity.\",\n",
783
+ " \"The storyline was underwhelming.\",\n",
784
+ " \"The book felt rushed in parts.\",\n",
785
+ " \"I didn’t enjoy the author’s style.\",\n",
786
+ " \"The pacing was inconsistent.\",\n",
787
+ " \"The characters lacked personality.\",\n",
788
+ " \"The overall experience was disappointing.\",\n",
789
+ " \"The conflict felt unconvincing.\",\n",
790
+ " \"The story failed to engage me.\",\n",
791
+ " \"It was not as compelling as I hoped.\",\n",
792
+ " \"The development felt shallow.\",\n",
793
+ " \"The book lacked emotional impact.\",\n",
794
+ " \"The ending felt abrupt.\",\n",
795
+ " \"The plot felt overly complicated.\",\n",
796
+ " \"The writing was monotonous.\",\n",
797
+ " \"The story didn’t hold my attention.\",\n",
798
+ " \"The characters seemed unrealistic.\",\n",
799
+ " \"The book felt overly long.\",\n",
800
+ " \"The central idea was poorly executed.\",\n",
801
+ " \"The narrative lacked focus.\",\n",
802
+ " \"The story felt unfinished.\",\n",
803
+ " \"The book was not memorable.\",\n",
804
+ " \"The pacing made it hard to stay engaged.\",\n",
805
+ " \"The themes were not explored deeply enough.\",\n",
806
+ " \"It failed to leave an impression.\",\n",
807
+ " \"The dialogue sounded unnatural.\",\n",
808
+ " \"The storyline felt weak.\",\n",
809
+ " \"The writing lacked energy.\",\n",
810
+ " \"The book was disappointing overall.\",\n",
811
+ " \"It did not deliver on its premise.\",\n",
812
+ " \"The plot was not compelling.\",\n",
813
+ " \"I wouldn’t recommend this book.\"\n",
814
+ " ]\n",
815
+ "}\n"
816
+ ]
817
+ },
818
+ {
819
+ "cell_type": "markdown",
820
+ "metadata": {
821
+ "id": "fQhfVaDmuULT"
822
+ },
823
+ "source": [
824
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
825
+ ]
826
+ },
827
+ {
828
+ "cell_type": "code",
829
+ "execution_count": 24,
830
+ "metadata": {
831
+ "id": "l2SRc3PjuTGM"
832
+ },
833
+ "outputs": [],
834
+ "source": [
835
+ "review_rows = []\n",
836
+ "for _, row in df_books.iterrows():\n",
837
+ " title = row['title']\n",
838
+ " sentiment_label = row['sentiment_label']\n",
839
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
840
+ " sampled_reviews = random.sample(review_pool, 10)\n",
841
+ " for review_text in sampled_reviews:\n",
842
+ " review_rows.append({\n",
843
+ " \"title\": title,\n",
844
+ " \"sentiment_label\": sentiment_label,\n",
845
+ " \"review_text\": review_text,\n",
846
+ " \"rating\": row['rating'],\n",
847
+ " \"popularity_score\": row['popularity_score']\n",
848
+ " })"
849
+ ]
850
+ },
851
+ {
852
+ "cell_type": "markdown",
853
+ "metadata": {
854
+ "id": "bmJMXF-Bukdm"
855
+ },
856
+ "source": [
857
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
858
+ ]
859
+ },
860
+ {
861
+ "cell_type": "code",
862
+ "execution_count": 28,
863
+ "metadata": {
864
+ "id": "ZUKUqZsuumsp"
865
+ },
866
+ "outputs": [],
867
+ "source": [
868
+ "df_reviews = pd.DataFrame(review_rows)\n",
869
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)\n"
870
+ ]
871
+ },
872
+ {
873
+ "cell_type": "markdown",
874
+ "source": [
875
+ "### *c. inputs for R*"
876
+ ],
877
+ "metadata": {
878
+ "id": "_602pYUS3gY5"
879
+ }
880
+ },
881
+ {
882
+ "cell_type": "code",
883
+ "execution_count": 26,
884
+ "metadata": {
885
+ "colab": {
886
+ "base_uri": "https://localhost:8080/"
887
+ },
888
+ "id": "3946e521",
889
+ "outputId": "0f60f9ef-4d44-4c1e-f0cc-6d27ef94d420"
890
+ },
891
+ "outputs": [
892
+ {
893
+ "output_type": "stream",
894
+ "name": "stdout",
895
+ "text": [
896
+ "✅ Wrote synthetic_title_level_features.csv\n",
897
+ "✅ Wrote synthetic_monthly_revenue_series.csv\n"
898
+ ]
899
+ }
900
+ ],
901
+ "source": [
902
+ "import numpy as np\n",
903
+ "\n",
904
+ "def _safe_num(s):\n",
905
+ " return pd.to_numeric(\n",
906
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
907
+ " errors=\"coerce\"\n",
908
+ " )\n",
909
+ "\n",
910
+ "# --- Clean book metadata (price/rating) ---\n",
911
+ "df_books_r = df_books.copy()\n",
912
+ "if \"price\" in df_books_r.columns:\n",
913
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
914
+ "if \"rating\" in df_books_r.columns:\n",
915
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
916
+ "\n",
917
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
918
+ "\n",
919
+ "# --- Clean sales ---\n",
920
+ "df_sales_r = df_sales.copy()\n",
921
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
922
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
923
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
924
+ "\n",
925
+ "# --- Clean reviews ---\n",
926
+ "df_reviews_r = df_reviews.copy()\n",
927
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
928
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
929
+ "if \"rating\" in df_reviews_r.columns:\n",
930
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
931
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
932
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
933
+ "\n",
934
+ "# --- Sentiment shares per title (from reviews) ---\n",
935
+ "sent_counts = (\n",
936
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
937
+ " .size()\n",
938
+ " .unstack(fill_value=0)\n",
939
+ ")\n",
940
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
941
+ " if lab not in sent_counts.columns:\n",
942
+ " sent_counts[lab] = 0\n",
943
+ "\n",
944
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
945
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
946
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
947
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
948
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
949
+ "sent_counts = sent_counts.reset_index()\n",
950
+ "\n",
951
+ "# --- Sales aggregation per title ---\n",
952
+ "sales_by_title = (\n",
953
+ " df_sales_r.dropna(subset=[\"title\"])\n",
954
+ " .groupby(\"title\", as_index=False)\n",
955
+ " .agg(\n",
956
+ " months_observed=(\"month\", \"nunique\"),\n",
957
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
958
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
959
+ " )\n",
960
+ ")\n",
961
+ "\n",
962
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
963
+ "df_title = (\n",
964
+ " sales_by_title\n",
965
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
966
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
967
+ " on=\"title\", how=\"left\")\n",
968
+ ")\n",
969
+ "\n",
970
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
971
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
972
+ "\n",
973
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
974
+ "print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
975
+ "\n",
976
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
977
+ "monthly_rev = (\n",
978
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
979
+ ")\n",
980
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
981
+ "\n",
982
+ "df_monthly = (\n",
983
+ " monthly_rev.dropna(subset=[\"month\"])\n",
984
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
985
+ " .sum()\n",
986
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
987
+ " .sort_values(\"month\")\n",
988
+ ")\n",
989
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
990
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
991
+ " df_monthly = (\n",
992
+ " df_sales_r.dropna(subset=[\"month\"])\n",
993
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
994
+ " .sum()\n",
995
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
996
+ " .sort_values(\"month\")\n",
997
+ " )\n",
998
+ "\n",
999
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1000
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1001
+ "print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
1002
+ ]
1003
+ },
1004
+ {
1005
+ "cell_type": "markdown",
1006
+ "metadata": {
1007
+ "id": "RYvGyVfXuo54"
1008
+ },
1009
+ "source": [
1010
+ "### *d. ✋🏻🛑⛔️ View the first few lines*"
1011
+ ]
1012
+ },
1013
+ {
1014
+ "cell_type": "code",
1015
+ "execution_count": 27,
1016
+ "metadata": {
1017
+ "colab": {
1018
+ "base_uri": "https://localhost:8080/",
1019
+ "height": 204
1020
+ },
1021
+ "id": "xfE8NMqOurKo",
1022
+ "outputId": "fef5de5e-d0d7-43c4-e491-a7dd00b8c5a6"
1023
+ },
1024
+ "outputs": [
1025
+ {
1026
+ "output_type": "execute_result",
1027
+ "data": {
1028
+ "text/plain": [
1029
+ " title sentiment_label \\\n",
1030
+ "0 A Light in the Attic neutral \n",
1031
+ "1 A Light in the Attic neutral \n",
1032
+ "2 A Light in the Attic neutral \n",
1033
+ "3 A Light in the Attic neutral \n",
1034
+ "4 A Light in the Attic neutral \n",
1035
+ "\n",
1036
+ " review_text rating popularity_score \n",
1037
+ "0 The book maintained a steady rhythm. Three 3 \n",
1038
+ "1 The dialogue was functional. Three 3 \n",
1039
+ "2 The structure was conventional. Three 3 \n",
1040
+ "3 The writing style was straightforward. Three 3 \n",
1041
+ "4 The characters were average. Three 3 "
1042
+ ],
1043
+ "text/html": [
1044
+ "\n",
1045
+ " <div id=\"df-3180012f-3478-4a03-b79b-0180cc7bbf63\" class=\"colab-df-container\">\n",
1046
+ " <div>\n",
1047
+ "<style scoped>\n",
1048
+ " .dataframe tbody tr th:only-of-type {\n",
1049
+ " vertical-align: middle;\n",
1050
+ " }\n",
1051
+ "\n",
1052
+ " .dataframe tbody tr th {\n",
1053
+ " vertical-align: top;\n",
1054
+ " }\n",
1055
+ "\n",
1056
+ " .dataframe thead th {\n",
1057
+ " text-align: right;\n",
1058
+ " }\n",
1059
+ "</style>\n",
1060
+ "<table border=\"1\" class=\"dataframe\">\n",
1061
+ " <thead>\n",
1062
+ " <tr style=\"text-align: right;\">\n",
1063
+ " <th></th>\n",
1064
+ " <th>title</th>\n",
1065
+ " <th>sentiment_label</th>\n",
1066
+ " <th>review_text</th>\n",
1067
+ " <th>rating</th>\n",
1068
+ " <th>popularity_score</th>\n",
1069
+ " </tr>\n",
1070
+ " </thead>\n",
1071
+ " <tbody>\n",
1072
+ " <tr>\n",
1073
+ " <th>0</th>\n",
1074
+ " <td>A Light in the Attic</td>\n",
1075
+ " <td>neutral</td>\n",
1076
+ " <td>The book maintained a steady rhythm.</td>\n",
1077
+ " <td>Three</td>\n",
1078
+ " <td>3</td>\n",
1079
+ " </tr>\n",
1080
+ " <tr>\n",
1081
+ " <th>1</th>\n",
1082
+ " <td>A Light in the Attic</td>\n",
1083
+ " <td>neutral</td>\n",
1084
+ " <td>The dialogue was functional.</td>\n",
1085
+ " <td>Three</td>\n",
1086
+ " <td>3</td>\n",
1087
+ " </tr>\n",
1088
+ " <tr>\n",
1089
+ " <th>2</th>\n",
1090
+ " <td>A Light in the Attic</td>\n",
1091
+ " <td>neutral</td>\n",
1092
+ " <td>The structure was conventional.</td>\n",
1093
+ " <td>Three</td>\n",
1094
+ " <td>3</td>\n",
1095
+ " </tr>\n",
1096
+ " <tr>\n",
1097
+ " <th>3</th>\n",
1098
+ " <td>A Light in the Attic</td>\n",
1099
+ " <td>neutral</td>\n",
1100
+ " <td>The writing style was straightforward.</td>\n",
1101
+ " <td>Three</td>\n",
1102
+ " <td>3</td>\n",
1103
+ " </tr>\n",
1104
+ " <tr>\n",
1105
+ " <th>4</th>\n",
1106
+ " <td>A Light in the Attic</td>\n",
1107
+ " <td>neutral</td>\n",
1108
+ " <td>The characters were average.</td>\n",
1109
+ " <td>Three</td>\n",
1110
+ " <td>3</td>\n",
1111
+ " </tr>\n",
1112
+ " </tbody>\n",
1113
+ "</table>\n",
1114
+ "</div>\n",
1115
+ " <div class=\"colab-df-buttons\">\n",
1116
+ "\n",
1117
+ " <div class=\"colab-df-container\">\n",
1118
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-3180012f-3478-4a03-b79b-0180cc7bbf63')\"\n",
1119
+ " title=\"Convert this dataframe to an interactive table.\"\n",
1120
+ " style=\"display:none;\">\n",
1121
+ "\n",
1122
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
1123
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
1124
+ " </svg>\n",
1125
+ " </button>\n",
1126
+ "\n",
1127
+ " <style>\n",
1128
+ " .colab-df-container {\n",
1129
+ " display:flex;\n",
1130
+ " gap: 12px;\n",
1131
+ " }\n",
1132
+ "\n",
1133
+ " .colab-df-convert {\n",
1134
+ " background-color: #E8F0FE;\n",
1135
+ " border: none;\n",
1136
+ " border-radius: 50%;\n",
1137
+ " cursor: pointer;\n",
1138
+ " display: none;\n",
1139
+ " fill: #1967D2;\n",
1140
+ " height: 32px;\n",
1141
+ " padding: 0 0 0 0;\n",
1142
+ " width: 32px;\n",
1143
+ " }\n",
1144
+ "\n",
1145
+ " .colab-df-convert:hover {\n",
1146
+ " background-color: #E2EBFA;\n",
1147
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
1148
+ " fill: #174EA6;\n",
1149
+ " }\n",
1150
+ "\n",
1151
+ " .colab-df-buttons div {\n",
1152
+ " margin-bottom: 4px;\n",
1153
+ " }\n",
1154
+ "\n",
1155
+ " [theme=dark] .colab-df-convert {\n",
1156
+ " background-color: #3B4455;\n",
1157
+ " fill: #D2E3FC;\n",
1158
+ " }\n",
1159
+ "\n",
1160
+ " [theme=dark] .colab-df-convert:hover {\n",
1161
+ " background-color: #434B5C;\n",
1162
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
1163
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
1164
+ " fill: #FFFFFF;\n",
1165
+ " }\n",
1166
+ " </style>\n",
1167
+ "\n",
1168
+ " <script>\n",
1169
+ " const buttonEl =\n",
1170
+ " document.querySelector('#df-3180012f-3478-4a03-b79b-0180cc7bbf63 button.colab-df-convert');\n",
1171
+ " buttonEl.style.display =\n",
1172
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
1173
+ "\n",
1174
+ " async function convertToInteractive(key) {\n",
1175
+ " const element = document.querySelector('#df-3180012f-3478-4a03-b79b-0180cc7bbf63');\n",
1176
+ " const dataTable =\n",
1177
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
1178
+ " [key], {});\n",
1179
+ " if (!dataTable) return;\n",
1180
+ "\n",
1181
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
1182
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
1183
+ " + ' to learn more about interactive tables.';\n",
1184
+ " element.innerHTML = '';\n",
1185
+ " dataTable['output_type'] = 'display_data';\n",
1186
+ " await google.colab.output.renderOutput(dataTable, element);\n",
1187
+ " const docLink = document.createElement('div');\n",
1188
+ " docLink.innerHTML = docLinkHtml;\n",
1189
+ " element.appendChild(docLink);\n",
1190
+ " }\n",
1191
+ " </script>\n",
1192
+ " </div>\n",
1193
+ "\n",
1194
+ "\n",
1195
+ " </div>\n",
1196
+ " </div>\n"
1197
+ ],
1198
+ "application/vnd.google.colaboratory.intrinsic+json": {
1199
+ "type": "dataframe",
1200
+ "variable_name": "df_reviews",
1201
+ "summary": "{\n \"name\": \"df_reviews\",\n \"rows\": 10000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"sentiment_label\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"neutral\",\n \"negative\",\n \"positive\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"review_text\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 150,\n \"samples\": [\n \"I highly recommend this book.\",\n \"I couldn\\u2019t connect with the characters.\",\n \"An outstanding contribution to the genre.\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"popularity_score\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 5,\n \"num_unique_values\": 5,\n \"samples\": [\n 2,\n 5,\n 4\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
1202
+ }
1203
+ },
1204
+ "metadata": {},
1205
+ "execution_count": 27
1206
+ }
1207
+ ],
1208
+ "source": [
1209
+ "df_reviews.head()"
1210
+ ]
1211
+ }
1212
+ ],
1213
+ "metadata": {
1214
+ "colab": {
1215
+ "collapsed_sections": [
1216
+ "jpASMyIQMaAq",
1217
+ "lquNYCbfL9IM",
1218
+ "0IWuNpxxYDJF",
1219
+ "oCdTsin2Yfp3",
1220
+ "T0TOeRC4Yrnn",
1221
+ "duI5dv3CZYvF",
1222
+ "qMjRKMBQZlJi",
1223
+ "p-1Pr2szaqLk",
1224
+ "SIaJUGIpaH4V",
1225
+ "pY4yCoIuaQqp",
1226
+ "n4-TaNTFgPak",
1227
+ "HnngRNTgacYt",
1228
+ "HF9F9HIzgT7Z",
1229
+ "T8AdKkmASq9a",
1230
+ "OhXbdGD5fH0c",
1231
+ "L2ak1HlcgoTe",
1232
+ "4IXZKcCSgxnq",
1233
+ "EhIjz9WohAmZ",
1234
+ "Gi4y9M9KuDWx",
1235
+ "fQhfVaDmuULT",
1236
+ "bmJMXF-Bukdm",
1237
+ "RYvGyVfXuo54"
1238
+ ],
1239
+ "provenance": []
1240
+ },
1241
+ "kernelspec": {
1242
+ "display_name": "Python 3",
1243
+ "name": "python3"
1244
+ },
1245
+ "language_info": {
1246
+ "name": "python"
1247
+ }
1248
+ },
1249
+ "nbformat": 4,
1250
+ "nbformat_minor": 0
1251
+ }
pythonanalysis.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
ranalysis.ipynb ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "75fd9cc6",
6
+ "metadata": {
7
+ "id": "75fd9cc6"
8
+ },
9
+ "source": [
10
+ "# **🤖 Benchmarking & Modeling**"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "fb807724",
16
+ "metadata": {
17
+ "id": "fb807724"
18
+ },
19
+ "source": [
20
+ "## **1.** 📦 Setup"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": 1,
26
+ "id": "d40cd131",
27
+ "metadata": {
28
+ "id": "d40cd131",
29
+ "colab": {
30
+ "base_uri": "https://localhost:8080/"
31
+ },
32
+ "outputId": "209c7503-01b6-4cfe-8290-54e66d049da5"
33
+ },
34
+ "outputs": [
35
+ {
36
+ "output_type": "stream",
37
+ "name": "stderr",
38
+ "text": [
39
+ "Installing packages into ‘/usr/local/lib/R/site-library’\n",
40
+ "(as ‘lib’ is unspecified)\n",
41
+ "\n"
42
+ ]
43
+ }
44
+ ],
45
+ "source": [
46
+ "\n",
47
+ "# Uncomment the next line once:\n",
48
+ "install.packages(c(\"readr\",\"dplyr\",\"stringr\",\"tidyr\",\"lubridate\",\"ggplot2\",\"forecast\",\"broom\",\"jsonlite\"), repos=\"https://cloud.r-project.org\")\n",
49
+ "\n",
50
+ "suppressPackageStartupMessages({\n",
51
+ " library(readr)\n",
52
+ " library(dplyr)\n",
53
+ " library(stringr)\n",
54
+ " library(tidyr)\n",
55
+ " library(lubridate)\n",
56
+ " library(ggplot2)\n",
57
+ " library(forecast)\n",
58
+ " library(broom)\n",
59
+ " library(jsonlite)\n",
60
+ "})"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "markdown",
65
+ "id": "f01d02e7",
66
+ "metadata": {
67
+ "id": "f01d02e7"
68
+ },
69
+ "source": [
70
+ "## **2.** ✅️ Load & inspect inputs"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": 2,
76
+ "id": "29e8f6ce",
77
+ "metadata": {
78
+ "colab": {
79
+ "base_uri": "https://localhost:8080/"
80
+ },
81
+ "id": "29e8f6ce",
82
+ "outputId": "d4da31c5-1df5-4b7a-9c46-bc25252aa243"
83
+ },
84
+ "outputs": [
85
+ {
86
+ "output_type": "stream",
87
+ "name": "stdout",
88
+ "text": [
89
+ "Loaded: 1000 rows (title-level), 18 rows (monthly)\n"
90
+ ]
91
+ }
92
+ ],
93
+ "source": [
94
+ "\n",
95
+ "must_exist <- function(path, label) {\n",
96
+ " if (!file.exists(path)) stop(paste0(\"Missing \", label, \": \", path))\n",
97
+ "}\n",
98
+ "\n",
99
+ "TITLE_PATH <- \"synthetic_title_level_features.csv\"\n",
100
+ "MONTH_PATH <- \"synthetic_monthly_revenue_series.csv\"\n",
101
+ "\n",
102
+ "must_exist(TITLE_PATH, \"TITLE_PATH\")\n",
103
+ "must_exist(MONTH_PATH, \"MONTH_PATH\")\n",
104
+ "\n",
105
+ "df_title <- read_csv(TITLE_PATH, show_col_types = FALSE)\n",
106
+ "df_month <- read_csv(MONTH_PATH, show_col_types = FALSE)\n",
107
+ "\n",
108
+ "cat(\"Loaded:\", nrow(df_title), \"rows (title-level),\", nrow(df_month), \"rows (monthly)\n",
109
+ "\")"
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": 3,
115
+ "id": "9fd04262",
116
+ "metadata": {
117
+ "colab": {
118
+ "base_uri": "https://localhost:8080/"
119
+ },
120
+ "id": "9fd04262",
121
+ "outputId": "f1441d75-8c8c-48d0-e33c-45e835de5ca1"
122
+ },
123
+ "outputs": [
124
+ {
125
+ "output_type": "stream",
126
+ "name": "stdout",
127
+ "text": [
128
+ "\u001b[90m# A tibble: 1 × 6\u001b[39m\n",
129
+ " n na_avg_revenue na_price na_rating na_share_pos na_share_neg\n",
130
+ " \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m\n",
131
+ "\u001b[90m1\u001b[39m \u001b[4m1\u001b[24m000 0 0 \u001b[4m1\u001b[24m000 0 0\n",
132
+ "Monthly rows after parsing: 18 \n"
133
+ ]
134
+ }
135
+ ],
136
+ "source": [
137
+ "\n",
138
+ "# ---------- helpers ----------\n",
139
+ "safe_num <- function(x) {\n",
140
+ " # strips anything that is not digit or dot\n",
141
+ " suppressWarnings(as.numeric(str_replace_all(as.character(x), \"[^0-9.]\", \"\")))\n",
142
+ "}\n",
143
+ "\n",
144
+ "parse_rating <- function(x) {\n",
145
+ " # Accept: 4, \"4\", \"4.0\", \"4/5\", \"4 out of 5\", \"⭐⭐⭐⭐\", etc.\n",
146
+ " x <- as.character(x)\n",
147
+ " x <- str_replace_all(x, \"⭐\", \"\")\n",
148
+ " x <- str_to_lower(x)\n",
149
+ " x <- str_replace_all(x, \"stars?\", \"\")\n",
150
+ " x <- str_replace_all(x, \"out of\", \"/\")\n",
151
+ " x <- str_replace_all(x, \"\\\\s+\", \"\")\n",
152
+ " x <- str_replace_all(x, \"[^0-9./]\", \"\")\n",
153
+ " suppressWarnings(as.numeric(str_extract(x, \"^[0-9.]+\")))\n",
154
+ "}\n",
155
+ "\n",
156
+ "parse_month <- function(x) {\n",
157
+ " x <- as.character(x)\n",
158
+ " # try YYYY-MM-DD, then YYYY-MM\n",
159
+ " out <- suppressWarnings(ymd(x))\n",
160
+ " if (mean(is.na(out)) > 0.5) out <- suppressWarnings(ymd(paste0(x, \"-01\")))\n",
161
+ " na_idx <- which(is.na(out))\n",
162
+ " if (length(na_idx) > 0) out[na_idx] <- suppressWarnings(ymd(paste0(x[na_idx], \"-01\")))\n",
163
+ " out\n",
164
+ "}\n",
165
+ "\n",
166
+ "# ---------- normalize keys ----------\n",
167
+ "df_title <- df_title %>% mutate(title = str_squish(as.character(title)))\n",
168
+ "df_month <- df_month %>% mutate(month = as.character(month))\n",
169
+ "\n",
170
+ "# ---------- parse numeric columns defensively ----------\n",
171
+ "need_cols_title <- c(\"title\",\"avg_revenue\",\"total_revenue\",\"price\",\"rating\",\"share_positive\",\"share_negative\",\"share_neutral\")\n",
172
+ "missing_title <- setdiff(need_cols_title, names(df_title))\n",
173
+ "if (length(missing_title) > 0) stop(paste0(\"df_title missing columns: \", paste(missing_title, collapse=\", \")))\n",
174
+ "\n",
175
+ "df_title <- df_title %>%\n",
176
+ " mutate(\n",
177
+ " avg_revenue = safe_num(avg_revenue),\n",
178
+ " total_revenue = safe_num(total_revenue),\n",
179
+ " price = safe_num(price),\n",
180
+ " rating = parse_rating(rating),\n",
181
+ " share_positive = safe_num(share_positive),\n",
182
+ " share_negative = safe_num(share_negative),\n",
183
+ " share_neutral = safe_num(share_neutral)\n",
184
+ " )\n",
185
+ "\n",
186
+ "# basic sanity stats\n",
187
+ "hyg <- df_title %>%\n",
188
+ " summarise(\n",
189
+ " n = n(),\n",
190
+ " na_avg_revenue = sum(is.na(avg_revenue)),\n",
191
+ " na_price = sum(is.na(price)),\n",
192
+ " na_rating = sum(is.na(rating)),\n",
193
+ " na_share_pos = sum(is.na(share_positive)),\n",
194
+ " na_share_neg = sum(is.na(share_negative))\n",
195
+ " )\n",
196
+ "\n",
197
+ "print(hyg)\n",
198
+ "\n",
199
+ "# monthly parsing\n",
200
+ "need_cols_month <- c(\"month\",\"total_revenue\")\n",
201
+ "missing_month <- setdiff(need_cols_month, names(df_month))\n",
202
+ "if (length(missing_month) > 0) stop(paste0(\"df_month missing columns: \", paste(missing_month, collapse=\", \")))\n",
203
+ "\n",
204
+ "df_month2 <- df_month %>%\n",
205
+ " mutate(\n",
206
+ " month = parse_month(month),\n",
207
+ " total_revenue = safe_num(total_revenue)\n",
208
+ " ) %>%\n",
209
+ " filter(!is.na(month)) %>%\n",
210
+ " arrange(month)\n",
211
+ "\n",
212
+ "cat(\"Monthly rows after parsing:\", nrow(df_month2), \"\\n\")"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "markdown",
217
+ "id": "b8971bc4",
218
+ "metadata": {
219
+ "id": "b8971bc4"
220
+ },
221
+ "source": [
222
+ "## **3.** 💾 Folder for R outputs for Hugging Face"
223
+ ]
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "execution_count": 5,
228
+ "id": "dfaa06b1",
229
+ "metadata": {
230
+ "colab": {
231
+ "base_uri": "https://localhost:8080/"
232
+ },
233
+ "id": "dfaa06b1",
234
+ "outputId": "2163cdcc-379d-4bc9-f951-1a5b90fa3930"
235
+ },
236
+ "outputs": [
237
+ {
238
+ "output_type": "stream",
239
+ "name": "stdout",
240
+ "text": [
241
+ "R outputs will be written to: /content/artifacts/r \n"
242
+ ]
243
+ }
244
+ ],
245
+ "source": [
246
+ "\n",
247
+ "ART_DIR <- \"artifacts\"\n",
248
+ "R_FIG_DIR <- file.path(ART_DIR, \"r\", \"figures\")\n",
249
+ "R_TAB_DIR <- file.path(ART_DIR, \"r\", \"tables\")\n",
250
+ "\n",
251
+ "dir.create(R_FIG_DIR, recursive = TRUE, showWarnings = FALSE)\n",
252
+ "dir.create(R_TAB_DIR, recursive = TRUE, showWarnings = FALSE)\n",
253
+ "\n",
254
+ "cat(\"R outputs will be written to:\", normalizePath(file.path(ART_DIR, \"r\"), winslash = \"/\"), \"\n",
255
+ "\")"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "id": "f880c72d",
261
+ "metadata": {
262
+ "id": "f880c72d"
263
+ },
264
+ "source": [
265
+ "## **4.** 🔮 Forecast book sales benchmarking with `accuracy()`"
266
+ ]
267
+ },
268
+ {
269
+ "cell_type": "markdown",
270
+ "source": [
271
+ "We benchmark **three** models on a holdout window (last *h* months):\n",
272
+ "- ARIMA + Fourier (seasonality upgrade)\n",
273
+ "- ETS\n",
274
+ "- Naive baseline\n",
275
+ "\n",
276
+ "Then we export:\n",
277
+ "- `accuracy_table.csv`\n",
278
+ "- `forecast_compare.png`\n",
279
+ "- `rmse_comparison.png`"
280
+ ],
281
+ "metadata": {
282
+ "id": "R0JZlzKegmzW"
283
+ },
284
+ "id": "R0JZlzKegmzW"
285
+ },
286
+ {
287
+ "cell_type": "code",
288
+ "execution_count": 6,
289
+ "id": "62e87992",
290
+ "metadata": {
291
+ "colab": {
292
+ "base_uri": "https://localhost:8080/",
293
+ "height": 85
294
+ },
295
+ "id": "62e87992",
296
+ "outputId": "f167d4d4-99b7-42ad-99ec-3f26b1cc58e2"
297
+ },
298
+ "outputs": [
299
+ {
300
+ "output_type": "stream",
301
+ "name": "stdout",
302
+ "text": [
303
+ "✅ Saved: artifacts/r/tables/accuracy_table.csv\n",
304
+ "✅ Saved: artifacts/r/figures/rmse_comparison.png\n"
305
+ ]
306
+ },
307
+ {
308
+ "output_type": "display_data",
309
+ "data": {
310
+ "text/html": [
311
+ "<strong>agg_record_2087323215:</strong> 2"
312
+ ],
313
+ "text/markdown": "**agg_record_2087323215:** 2",
314
+ "text/latex": "\\textbf{agg\\textbackslash{}\\_record\\textbackslash{}\\_2087323215:} 2",
315
+ "text/plain": [
316
+ "agg_record_2087323215 \n",
317
+ " 2 "
318
+ ]
319
+ },
320
+ "metadata": {}
321
+ },
322
+ {
323
+ "output_type": "stream",
324
+ "name": "stdout",
325
+ "text": [
326
+ "✅ Saved: artifacts/r/figures/forecast_compare.png\n"
327
+ ]
328
+ }
329
+ ],
330
+ "source": [
331
+ "\n",
332
+ "# Build monthly ts\n",
333
+ "start_year <- year(min(df_month2$month, na.rm = TRUE))\n",
334
+ "start_mon <- month(min(df_month2$month, na.rm = TRUE))\n",
335
+ "\n",
336
+ "y <- ts(df_month2$total_revenue, frequency = 12, start = c(start_year, start_mon))\n",
337
+ "\n",
338
+ "# holdout size: min(6, 20% of series), at least 1\n",
339
+ "h_test <- min(6, max(1, floor(length(y) / 5)))\n",
340
+ "train_ts <- head(y, length(y) - h_test)\n",
341
+ "test_ts <- tail(y, h_test)\n",
342
+ "\n",
343
+ "# Model A: ARIMA + Fourier\n",
344
+ "K <- 2\n",
345
+ "xreg_train <- fourier(train_ts, K = K)\n",
346
+ "fit_arima <- auto.arima(train_ts, xreg = xreg_train)\n",
347
+ "xreg_future <- fourier(train_ts, K = K, h = h_test)\n",
348
+ "fc_arima <- forecast(fit_arima, xreg = xreg_future, h = h_test)\n",
349
+ "\n",
350
+ "# Model B: ETS\n",
351
+ "fit_ets <- ets(train_ts)\n",
352
+ "fc_ets <- forecast(fit_ets, h = h_test)\n",
353
+ "\n",
354
+ "# Model C: Naive baseline\n",
355
+ "fc_naive <- naive(train_ts, h = h_test)\n",
356
+ "\n",
357
+ "# accuracy() tables\n",
358
+ "acc_arima <- as.data.frame(accuracy(fc_arima, test_ts))\n",
359
+ "acc_ets <- as.data.frame(accuracy(fc_ets, test_ts))\n",
360
+ "acc_naive <- as.data.frame(accuracy(fc_naive, test_ts))\n",
361
+ "\n",
362
+ "accuracy_tbl <- bind_rows(\n",
363
+ " acc_arima %>% mutate(model = \"ARIMA+Fourier\"),\n",
364
+ " acc_ets %>% mutate(model = \"ETS\"),\n",
365
+ " acc_naive %>% mutate(model = \"Naive\")\n",
366
+ ") %>% relocate(model)\n",
367
+ "\n",
368
+ "write_csv(accuracy_tbl, file.path(R_TAB_DIR, \"accuracy_table.csv\"))\n",
369
+ "cat(\"✅ Saved: artifacts/r/tables/accuracy_table.csv\\n\")\n",
370
+ "\n",
371
+ "# RMSE bar chart\n",
372
+ "p_rmse <- ggplot(accuracy_tbl, aes(x = reorder(model, RMSE), y = RMSE)) +\n",
373
+ " geom_col() +\n",
374
+ " coord_flip() +\n",
375
+ " labs(title = \"Forecast model comparison (RMSE on holdout)\", x = \"\", y = \"RMSE\") +\n",
376
+ " theme_minimal()\n",
377
+ "\n",
378
+ "ggsave(file.path(R_FIG_DIR, \"rmse_comparison.png\"), p_rmse, width = 8, height = 4, dpi = 160)\n",
379
+ "cat(\"✅ Saved: artifacts/r/figures/rmse_comparison.png\\n\")\n",
380
+ "\n",
381
+ "# Side-by-side forecast plots (simple, no extra deps)\n",
382
+ "png(file.path(R_FIG_DIR, \"forecast_compare.png\"), width = 1200, height = 500)\n",
383
+ "par(mfrow = c(1, 3))\n",
384
+ "plot(fc_arima, main = \"ARIMA + Fourier\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
385
+ "plot(fc_ets, main = \"ETS\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
386
+ "plot(fc_naive, main = \"Naive\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
387
+ "dev.off()\n",
388
+ "cat(\"✅ Saved: artifacts/r/figures/forecast_compare.png\\n\")"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "markdown",
393
+ "id": "30bc017b",
394
+ "metadata": {
395
+ "id": "30bc017b"
396
+ },
397
+ "source": [
398
+ "## **5.** 💾 Some R metadata for Hugging Face"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "code",
403
+ "execution_count": 7,
404
+ "id": "645cb12b",
405
+ "metadata": {
406
+ "colab": {
407
+ "base_uri": "https://localhost:8080/"
408
+ },
409
+ "id": "645cb12b",
410
+ "outputId": "d6dc6874-c2f9-46e8-b93d-c03aa732d9b5"
411
+ },
412
+ "outputs": [
413
+ {
414
+ "output_type": "stream",
415
+ "name": "stdout",
416
+ "text": [
417
+ "✅ Saved: artifacts/r/tables/r_meta.json\n",
418
+ "DONE. R artifacts written to: artifacts/r \n"
419
+ ]
420
+ }
421
+ ],
422
+ "source": [
423
+ "# =========================================================\n",
424
+ "# Metadata export (aligned with current notebook objects)\n",
425
+ "# =========================================================\n",
426
+ "\n",
427
+ "meta <- list(\n",
428
+ "\n",
429
+ " # ---------------------------\n",
430
+ " # Dataset footprint\n",
431
+ " # ---------------------------\n",
432
+ " n_titles = nrow(df_title),\n",
433
+ " n_months = nrow(df_month2),\n",
434
+ "\n",
435
+ " # ---------------------------\n",
436
+ " # Forecasting info\n",
437
+ " # (only if these objects exist in your forecasting section)\n",
438
+ " # ---------------------------\n",
439
+ " forecasting = list(\n",
440
+ " holdout_h = h_test,\n",
441
+ " arima_order = forecast::arimaorder(fit_arima),\n",
442
+ " ets_method = fit_ets$method\n",
443
+ " )\n",
444
+ ")\n",
445
+ "\n",
446
+ "jsonlite::write_json(\n",
447
+ " meta,\n",
448
+ " path = file.path(R_TAB_DIR, \"r_meta.json\"),\n",
449
+ " pretty = TRUE,\n",
450
+ " auto_unbox = TRUE\n",
451
+ ")\n",
452
+ "\n",
453
+ "cat(\"✅ Saved: artifacts/r/tables/r_meta.json\\n\")\n",
454
+ "cat(\"DONE. R artifacts written to:\", file.path(ART_DIR, \"r\"), \"\\n\")\n"
455
+ ]
456
+ },
457
+ {
458
+ "cell_type": "code",
459
+ "source": [
460
+ "fastapi\n",
461
+ "uvicorn[standard]\n",
462
+ "from fastapi import FastAPI\n",
463
+ "\n",
464
+ "app = FastAPI()\n",
465
+ "\n",
466
+ "@app.get(\"/\")\n",
467
+ "def greet_json():\n",
468
+ " return {\"Hello\": \"World!\"}\n",
469
+ "# Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker\n",
470
+ "# you will also find guides on how best to write your Dockerfile\n",
471
+ "\n",
472
+ "FROM python:3.9\n",
473
+ "\n",
474
+ "RUN useradd -m -u 1000 user\n",
475
+ "USER user\n",
476
+ "ENV PATH=\"/home/user/.local/bin:$PATH\"\n",
477
+ "\n",
478
+ "WORKDIR /app\n",
479
+ "\n",
480
+ "COPY --chown=user ./requirements.txt requirements.txt\n",
481
+ "RUN pip install --no-cache-dir --upgrade -r requirements.txt\n",
482
+ "\n",
483
+ "COPY --chown=user . /app\n",
484
+ "CMD [\"uvicorn\", \"app:app\", \"--host\", \"0.0.0.0\", \"--port\", \"7860\"]\n",
485
+ "git add requirements.txt app.py Dockerfile && git commit -m 'Add application file' && git push"
486
+ ],
487
+ "metadata": {
488
+ "colab": {
489
+ "base_uri": "https://localhost:8080/",
490
+ "height": 122
491
+ },
492
+ "id": "4rOuIinoGxq9",
493
+ "outputId": "77f07a5c-6368-46c5-a2c6-044426d1ae29"
494
+ },
495
+ "id": "4rOuIinoGxq9",
496
+ "execution_count": 8,
497
+ "outputs": [
498
+ {
499
+ "output_type": "error",
500
+ "ename": "ERROR",
501
+ "evalue": "Error in parse(text = input): <text>:3:6: unexpected symbol\n2: uvicorn[standard]\n3: from fastapi\n ^\n",
502
+ "traceback": [
503
+ "Error in parse(text = input): <text>:3:6: unexpected symbol\n2: uvicorn[standard]\n3: from fastapi\n ^\nTraceback:\n"
504
+ ]
505
+ }
506
+ ]
507
+ }
508
+ ],
509
+ "metadata": {
510
+ "colab": {
511
+ "provenance": [],
512
+ "collapsed_sections": [
513
+ "f01d02e7",
514
+ "b8971bc4",
515
+ "f880c72d",
516
+ "30bc017b"
517
+ ]
518
+ },
519
+ "kernelspec": {
520
+ "name": "ir",
521
+ "display_name": "R"
522
+ },
523
+ "language_info": {
524
+ "name": "R"
525
+ }
526
+ },
527
+ "nbformat": 4,
528
+ "nbformat_minor": 5
529
+ }