File size: 29,434 Bytes
440e9c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4ba6aba8"
   },
   "source": [
    "# \ud83e\udd16 **Data Collection, Creation, Storage, and Processing**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jpASMyIQMaAq"
   },
   "source": [
    "## **1.** \ud83d\udce6 Install required packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "f48c8f8c",
    "outputId": "13d0dd5e-82c6-489f-b1f0-e970186a4eb7"
   },
   "outputs": [],
   "source": [
    "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lquNYCbfL9IM"
   },
   "source": [
    "## **2.** \u26cf Web-scrape all book titles, prices, and ratings from books.toscrape.com"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0IWuNpxxYDJF"
   },
   "source": [
    "### *a. Initial setup*\n",
    "Define the base url of the website you will scrape as well as how and what you will scrape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "91d52125"
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import pandas as pd\n",
    "import time\n",
    "\n",
    "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
    "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
    "\n",
    "titles, prices, ratings = [], [], []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oCdTsin2Yfp3"
   },
   "source": [
    "### *b. Fill titles, prices, and ratings from the web pages*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "xqO5Y3dnYhxt"
   },
   "outputs": [],
   "source": [
    "# Loop through all 50 pages\n",
    "for page in range(1, 51):\n",
    "    url = base_url.format(page)\n",
    "    response = requests.get(url, headers=headers)\n",
    "    soup = BeautifulSoup(response.content, \"html.parser\")\n",
    "    books = soup.find_all(\"article\", class_=\"product_pod\")\n",
    "\n",
    "    for book in books:\n",
    "        titles.append(book.h3.a[\"title\"])\n",
    "        prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
    "        ratings.append(book.p.get(\"class\")[1])\n",
    "\n",
    "    time.sleep(0.5)  # polite scraping delay"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "T0TOeRC4Yrnn"
   },
   "source": [
    "### *c. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "l5FkkNhUYTHh"
   },
   "outputs": [],
   "source": [
    "df_books = pd.DataFrame({\n",
    "    \"title\": titles,\n",
    "    \"price\": prices,\n",
    "    \"rating\": ratings\n",
    "})\n",
    "print(f\"Scraped {len(df_books)} books.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "duI5dv3CZYvF"
   },
   "source": [
    "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "lC1U_YHtZifh"
   },
   "outputs": [],
   "source": [
    "# \ud83d\udcbe Save to CSV\n",
    "df_books.to_csv(\"books_data.csv\", index=False)\n",
    "\n",
    "# \ud83d\udcbe Or save to Excel\n",
    "# df_books.to_excel(\"books_data.xlsx\", index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qMjRKMBQZlJi"
   },
   "source": [
    "### *e. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f View first fiew lines*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 206
    },
    "id": "O_wIvTxYZqCK",
    "outputId": "349b36b0-c008-4fd5-d4a4-dba38ae18337"
   },
   "outputs": [],
   "source": [
    "df_books.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "p-1Pr2szaqLk"
   },
   "source": [
    "## **3.** \ud83e\udde9 Create a meaningful connection between real & synthetic datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "SIaJUGIpaH4V"
   },
   "source": [
    "### *a. Initial setup*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "-gPXGcRPuV_9"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import random\n",
    "from datetime import datetime\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "random.seed(2025)\n",
    "np.random.seed(2025)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pY4yCoIuaQqp"
   },
   "source": [
    "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "mnd5hdAbaNjz"
   },
   "outputs": [],
   "source": [
    "def generate_popularity_score(rating):\n",
    "    base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
    "    trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
    "    return int(np.clip(base + trend_factor, 1, 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "n4-TaNTFgPak"
   },
   "source": [
    "### *c. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f Run the function to create a \"popularity_score\" column from \"rating\"*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "V-G3OCUCgR07"
   },
   "outputs": [],
   "source": [
    "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)\n",
    "df_books[[\"title\", \"rating\", \"popularity_score\"]].head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HnngRNTgacYt"
   },
   "source": [
    "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "kUtWmr8maZLZ"
   },
   "outputs": [],
   "source": [
    "def get_sentiment(popularity_score):\n",
    "    if popularity_score <= 2:\n",
    "        return \"negative\"\n",
    "    elif popularity_score == 3:\n",
    "        return \"neutral\"\n",
    "    else:\n",
    "        return \"positive\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HF9F9HIzgT7Z"
   },
   "source": [
    "### *e. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "tafQj8_7gYCG"
   },
   "outputs": [],
   "source": [
    "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)\n",
    "df_books[[\"title\", \"rating\", \"popularity_score\", \"sentiment_label\"]].head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "T8AdKkmASq9a"
   },
   "source": [
    "## **4.** \ud83d\udcc8 Generate synthetic book sales data of 18 months"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "OhXbdGD5fH0c"
   },
   "source": [
    "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "qkVhYPXGbgEn"
   },
   "outputs": [],
   "source": [
    "def generate_sales_profile(sentiment):\n    months = pd.date_range(end=datetime.today(), periods=18, freq=\"ME\")\n\n    if sentiment == \"positive\":\n        base = random.randint(200, 300)\n        trend = np.linspace(base, base + random.randint(20, 60), len(months))\n    elif sentiment == \"negative\":\n        base = random.randint(20, 80)\n        trend = np.linspace(base, base - random.randint(10, 30), len(months))\n    else:  # neutral\n        base = random.randint(80, 160)\n        trend = np.full(len(months), base + random.randint(-10, 10))\n\n    seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n    noise = np.random.normal(0, 5, len(months))\n    monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n\n    return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "L2ak1HlcgoTe"
   },
   "source": [
    "### *b. Run the function as part of building sales_data*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "SlJ24AUafoDB"
   },
   "outputs": [],
   "source": [
    "sales_data = []\n",
    "for _, row in df_books.iterrows():\n",
    "    records = generate_sales_profile(row[\"sentiment_label\"])\n",
    "    for month, units in records:\n",
    "        sales_data.append({\n",
    "            \"title\": row[\"title\"],\n",
    "            \"month\": month,\n",
    "            \"units_sold\": units,\n",
    "            \"sentiment_label\": row[\"sentiment_label\"]\n",
    "        })"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4IXZKcCSgxnq"
   },
   "source": [
    "### *c. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f Create a df_sales DataFrame from sales_data*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "wcN6gtiZg-ws"
   },
   "outputs": [],
   "source": [
    "df_sales = pd.DataFrame(sales_data)\n",
    "print(f\"Generated {len(df_sales)} sales records.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EhIjz9WohAmZ"
   },
   "source": [
    "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "MzbZvLcAhGaH",
    "outputId": "c692bb04-7263-4115-a2ba-c72fe0180722"
   },
   "outputs": [],
   "source": [
    "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
    "\n",
    "print(df_sales.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7g9gqBgQMtJn"
   },
   "source": [
    "## **5.** \ud83c\udfaf Generate synthetic customer reviews"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Gi4y9M9KuDWx"
   },
   "source": [
    "### *a. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f 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*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "b3cd2a50"
   },
   "outputs": [],
   "source": [
    "synthetic_reviews_by_sentiment = {\n",
    "    \"positive\": [\n",
    "        \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
    "        \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
    "        \"One of the best books I've read this year \u2014 inspiring and emotionally rich.\",\n",
    "        \"The author's storytelling was vivid and powerful. Highly recommended!\",\n",
    "        \"An absolute masterpiece. I couldn't put it down from start to finish.\",\n",
    "        \"Gripping, intelligent, and beautifully crafted \u2014 I loved every page.\",\n",
    "        \"The emotional depth and layered narrative were just perfect.\",\n",
    "        \"A thought-provoking journey with stunning character development.\",\n",
    "        \"Everything about this book just clicked. A top-tier read!\",\n",
    "        \"A flawless blend of emotion, intrigue, and style. Truly impressive.\",\n",
    "        \"Absolutely stunning work of fiction. Five stars from me.\",\n",
    "        \"Remarkably executed with breathtaking prose.\",\n",
    "        \"The pacing was perfect and I was hooked from page one.\",\n",
    "        \"Heartfelt and hopeful \u2014 a story well worth telling.\",\n",
    "        \"A vivid journey through complex emotions and stunning imagery.\",\n",
    "        \"This book had soul. Every word felt like it mattered.\",\n",
    "        \"It delivered more than I ever expected. Powerful and wise.\",\n",
    "        \"The characters leapt off the page and into my heart.\",\n",
    "        \"I could see every scene clearly in my mind \u2014 beautifully descriptive.\",\n",
    "        \"Refreshing, original, and impossible to forget.\",\n",
    "        \"A radiant celebration of resilience and love.\",\n",
    "        \"Powerful themes handled with grace and insight.\",\n",
    "        \"An unforgettable literary experience.\",\n",
    "        \"The best book club pick we've had all year.\",\n",
    "        \"A layered, lyrical narrative that resonates deeply.\",\n",
    "        \"Surprising, profound, and deeply humane.\",\n",
    "        \"One of those rare books I wish I could read again for the first time.\",\n",
    "        \"Both epic and intimate \u2014 a perfect balance.\",\n",
    "        \"It reads like a love letter to the human spirit.\",\n",
    "        \"Satisfying and uplifting with a memorable ending.\",\n",
    "        \"This novel deserves every bit of praise it gets.\",\n",
    "        \"Introspective, emotional, and elegantly composed.\",\n",
    "        \"A tour de force in contemporary fiction.\",\n",
    "        \"Left me smiling, teary-eyed, and completely fulfilled.\",\n",
    "        \"A novel with the rare ability to entertain and enlighten.\",\n",
    "        \"Incredibly moving. I highlighted so many lines.\",\n",
    "        \"A smart, sensitive take on relationships and identity.\",\n",
    "        \"You feel wiser by the end of it.\",\n",
    "        \"A gorgeously crafted tale about hope and second chances.\",\n",
    "        \"Poignant and real \u2014 a beautiful escape.\",\n",
    "        \"Brims with insight and authenticity.\",\n",
    "        \"Compelling characters and a satisfying plot.\",\n",
    "        \"An empowering and important read.\",\n",
    "        \"Elegantly crafted and deeply humane.\",\n",
    "        \"Taut storytelling that never lets go.\",\n",
    "        \"Each chapter offered a new treasure.\",\n",
    "        \"Lyrical writing that stays with you.\",\n",
    "        \"A wonderful blend of passion and thoughtfulness.\",\n",
    "        \"Uplifting, honest, and completely engrossing.\",\n",
    "        \"This one made me believe in storytelling again.\",\n",
    "    ],\n",
    "    \"neutral\": [\n",
    "        \"An average book \u2014 not great, but not bad either.\",\n",
    "        \"Some parts really stood out, others felt a bit flat.\",\n",
    "        \"It was okay overall. A decent way to pass the time.\",\n",
    "        \"The writing was fine, though I didn't fully connect with the story.\",\n",
    "        \"Had a few memorable moments but lacked depth in some areas.\",\n",
    "        \"A mixed experience \u2014 neither fully engaging nor forgettable.\",\n",
    "        \"There was potential, but it didn't quite come together for me.\",\n",
    "        \"A reasonable effort that just didn't leave a lasting impression.\",\n",
    "        \"Serviceable but not something I'd go out of my way to recommend.\",\n",
    "        \"Not much to dislike, but not much to rave about either.\",\n",
    "        \"It had its strengths, though they didn't shine consistently.\",\n",
    "        \"I'm on the fence \u2014 parts were enjoyable, others not so much.\",\n",
    "        \"The book had a unique concept but lacked execution.\",\n",
    "        \"A middle-of-the-road read.\",\n",
    "        \"Engaging at times, but it lost momentum.\",\n",
    "        \"Would have benefited from stronger character development.\",\n",
    "        \"It passed the time, but I wouldn't reread it.\",\n",
    "        \"The plot had some holes that affected immersion.\",\n",
    "        \"Mediocre pacing made it hard to stay invested.\",\n",
    "        \"Satisfying in parts, underwhelming in others.\",\n",
    "        \"Neutral on this one \u2014 didn't love it or hate it.\",\n",
    "        \"Fairly forgettable but with glimpses of promise.\",\n",
    "        \"The themes were solid, but not well explored.\",\n",
    "        \"Competent, just not compelling.\",\n",
    "        \"Had moments of clarity and moments of confusion.\",\n",
    "        \"I didn't regret reading it, but I wouldn't recommend it.\",\n",
    "        \"Readable, yet uninspired.\",\n",
    "        \"There was a spark, but it didn't ignite.\",\n",
    "        \"A slow burn that didn't quite catch fire.\",\n",
    "        \"I expected more nuance given the premise.\",\n",
    "        \"A safe, inoffensive choice.\",\n",
    "        \"Some parts lagged, others piqued my interest.\",\n",
    "        \"Decent, but needed polish.\",\n",
    "        \"Moderately engaging but didn't stick the landing.\",\n",
    "        \"It simply lacked that emotional punch.\",\n",
    "        \"Just fine \u2014 no better, no worse.\",\n",
    "        \"Some thoughtful passages amid otherwise dry writing.\",\n",
    "        \"I appreciated the ideas more than the execution.\",\n",
    "        \"Struggled with cohesion.\",\n",
    "        \"Solidly average.\",\n",
    "        \"Good on paper, flat in practice.\",\n",
    "        \"A few bright spots, but mostly dim.\",\n",
    "        \"The kind of book that fades from memory.\",\n",
    "        \"It scratched the surface but didn't dig deep.\",\n",
    "        \"Standard fare with some promise.\",\n",
    "        \"Okay, but not memorable.\",\n",
    "        \"Had potential that went unrealized.\",\n",
    "        \"Could have been tighter, sharper, deeper.\",\n",
    "        \"A blend of mediocrity and mild interest.\",\n",
    "        \"I kept reading, but barely.\",\n",
    "    ],\n",
    "    \"negative\": [\n",
    "        \"I struggled to get through this one \u2014 it just didn't grab me.\",\n",
    "        \"The plot was confusing and the characters felt underdeveloped.\",\n",
    "        \"Disappointing. I had high hopes, but they weren't met.\",\n",
    "        \"Uninspired writing and a story that never quite took off.\",\n",
    "        \"Unfortunately, it was dull and predictable throughout.\",\n",
    "        \"The pacing dragged and I couldn't find anything compelling.\",\n",
    "        \"This felt like a chore to read \u2014 lacked heart and originality.\",\n",
    "        \"Nothing really worked for me in this book.\",\n",
    "        \"A frustrating read that left me unsatisfied.\",\n",
    "        \"I kept hoping it would improve, but it never did.\",\n",
    "        \"The characters didn't feel real, and the dialogue was forced.\",\n",
    "        \"I couldn't connect with the story at all.\",\n",
    "        \"A slow, meandering narrative with little payoff.\",\n",
    "        \"Tried too hard to be deep, but just felt empty.\",\n",
    "        \"The tone was uneven and confusing.\",\n",
    "        \"Way too repetitive and lacking progression.\",\n",
    "        \"The ending was abrupt and unsatisfying.\",\n",
    "        \"No emotional resonance \u2014 I felt nothing throughout.\",\n",
    "        \"I expected much more, but this fell flat.\",\n",
    "        \"Poorly edited and full of clich\u00e9s.\",\n",
    "        \"The premise was interesting, but poorly executed.\",\n",
    "        \"Just didn't live up to the praise.\",\n",
    "        \"A disjointed mess from start to finish.\",\n",
    "        \"Overly long and painfully dull.\",\n",
    "        \"Dialogue that felt robotic and unrealistic.\",\n",
    "        \"A hollow shell of what it could've been.\",\n",
    "        \"It lacked a coherent structure.\",\n",
    "        \"More confusing than complex.\",\n",
    "        \"Reading it felt like a task, not a treat.\",\n",
    "        \"There was no tension, no emotion \u2014 just words.\",\n",
    "        \"Characters with no motivation or development.\",\n",
    "        \"The plot twists were nonsensical.\",\n",
    "        \"Regret buying this book.\",\n",
    "        \"Nothing drew me in, nothing made me stay.\",\n",
    "        \"Too many subplots and none were satisfying.\",\n",
    "        \"Tedious and unimaginative.\",\n",
    "        \"Like reading a rough draft.\",\n",
    "        \"Disjointed, distant, and disappointing.\",\n",
    "        \"A lot of buildup with no payoff.\",\n",
    "        \"I don't understand the hype.\",\n",
    "        \"This book simply didn't work.\",\n",
    "        \"Forgettable in every sense.\",\n",
    "        \"More effort should've gone into editing.\",\n",
    "        \"The story lost its way early on.\",\n",
    "        \"It dragged endlessly.\",\n",
    "        \"I kept checking how many pages were left.\",\n",
    "        \"This lacked vision and clarity.\",\n",
    "        \"I expected substance \u2014 got fluff.\",\n",
    "        \"It failed to make me care.\",\n",
    "    ]\n",
    "}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fQhfVaDmuULT"
   },
   "source": [
    "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "l2SRc3PjuTGM"
   },
   "outputs": [],
   "source": [
    "review_rows = []\n",
    "for _, row in df_books.iterrows():\n",
    "    title = row['title']\n",
    "    sentiment_label = row['sentiment_label']\n",
    "    review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
    "    sampled_reviews = random.sample(review_pool, 10)\n",
    "    for review_text in sampled_reviews:\n",
    "        review_rows.append({\n",
    "            \"title\": title,\n",
    "            \"sentiment_label\": sentiment_label,\n",
    "            \"review_text\": review_text,\n",
    "            \"rating\": row['rating'],\n",
    "            \"popularity_score\": row['popularity_score']\n",
    "        })"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bmJMXF-Bukdm"
   },
   "source": [
    "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ZUKUqZsuumsp"
   },
   "outputs": [],
   "source": [
    "df_reviews = pd.DataFrame(review_rows)\n",
    "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "source": [
    "### *c. inputs for R*"
   ],
   "metadata": {
    "id": "_602pYUS3gY5"
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "3946e521",
    "outputId": "514d7bef-0488-4933-b03c-953b9e8a7f66"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def _safe_num(s):\n",
    "    return pd.to_numeric(\n",
    "        pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
    "        errors=\"coerce\"\n",
    "    )\n",
    "\n",
    "# --- Clean book metadata (price/rating) ---\n",
    "df_books_r = df_books.copy()\n",
    "if \"price\" in df_books_r.columns:\n",
    "    df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
    "if \"rating\" in df_books_r.columns:\n",
    "    df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
    "\n",
    "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
    "\n",
    "# --- Clean sales ---\n",
    "df_sales_r = df_sales.copy()\n",
    "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
    "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
    "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
    "\n",
    "# --- Clean reviews ---\n",
    "df_reviews_r = df_reviews.copy()\n",
    "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
    "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
    "if \"rating\" in df_reviews_r.columns:\n",
    "    df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
    "if \"popularity_score\" in df_reviews_r.columns:\n",
    "    df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
    "\n",
    "# --- Sentiment shares per title (from reviews) ---\n",
    "sent_counts = (\n",
    "    df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
    "    .size()\n",
    "    .unstack(fill_value=0)\n",
    ")\n",
    "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
    "    if lab not in sent_counts.columns:\n",
    "        sent_counts[lab] = 0\n",
    "\n",
    "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
    "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
    "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
    "sent_counts[\"share_neutral\"]  = sent_counts[\"neutral\"]  / den\n",
    "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
    "sent_counts = sent_counts.reset_index()\n",
    "\n",
    "# --- Sales aggregation per title ---\n",
    "sales_by_title = (\n",
    "    df_sales_r.dropna(subset=[\"title\"])\n",
    "    .groupby(\"title\", as_index=False)\n",
    "    .agg(\n",
    "        months_observed=(\"month\", \"nunique\"),\n",
    "        avg_units_sold=(\"units_sold\", \"mean\"),\n",
    "        total_units_sold=(\"units_sold\", \"sum\"),\n",
    "    )\n",
    ")\n",
    "\n",
    "# --- Title-level features (join sales + books + sentiment) ---\n",
    "df_title = (\n",
    "    sales_by_title\n",
    "    .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
    "    .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
    "           on=\"title\", how=\"left\")\n",
    ")\n",
    "\n",
    "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
    "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
    "\n",
    "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
    "print(\"\u2705 Wrote synthetic_title_level_features.csv\")\n",
    "\n",
    "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
    "monthly_rev = (\n",
    "    df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
    ")\n",
    "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
    "\n",
    "df_monthly = (\n",
    "    monthly_rev.dropna(subset=[\"month\"])\n",
    "    .groupby(\"month\", as_index=False)[\"revenue\"]\n",
    "    .sum()\n",
    "    .rename(columns={\"revenue\": \"total_revenue\"})\n",
    "    .sort_values(\"month\")\n",
    ")\n",
    "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
    "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
    "    df_monthly = (\n",
    "        df_sales_r.dropna(subset=[\"month\"])\n",
    "        .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
    "        .sum()\n",
    "        .rename(columns={\"units_sold\": \"total_revenue\"})\n",
    "        .sort_values(\"month\")\n",
    "    )\n",
    "\n",
    "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
    "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
    "print(\"\u2705 Wrote synthetic_monthly_revenue_series.csv\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RYvGyVfXuo54"
   },
   "source": [
    "### *d. \u270b\ud83c\udffb\ud83d\uded1\u26d4\ufe0f View the first few lines*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "xfE8NMqOurKo",
    "outputId": "191730ba-d5e2-4df7-97d2-99feb0b704af"
   },
   "outputs": [],
   "source": [
    "print(df_reviews.head())"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "jpASMyIQMaAq",
    "lquNYCbfL9IM",
    "0IWuNpxxYDJF",
    "oCdTsin2Yfp3",
    "T0TOeRC4Yrnn",
    "duI5dv3CZYvF",
    "qMjRKMBQZlJi",
    "p-1Pr2szaqLk",
    "SIaJUGIpaH4V",
    "pY4yCoIuaQqp",
    "n4-TaNTFgPak",
    "HnngRNTgacYt",
    "HF9F9HIzgT7Z",
    "T8AdKkmASq9a",
    "OhXbdGD5fH0c",
    "L2ak1HlcgoTe",
    "4IXZKcCSgxnq",
    "EhIjz9WohAmZ",
    "Gi4y9M9KuDWx",
    "fQhfVaDmuULT",
    "bmJMXF-Bukdm",
    "RYvGyVfXuo54"
   ],
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}