Atulkumar001 commited on
Commit
8fc668a
·
verified ·
1 Parent(s): 68ce292

Update build_database.py

Browse files
Files changed (1) hide show
  1. build_database.py +310 -1
build_database.py CHANGED
@@ -1 +1,310 @@
1
- print("Database builder ready")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import pickle
4
+ import requests
5
+ import pandas as pd
6
+ import numpy as np
7
+ import faiss
8
+
9
+ from bs4 import BeautifulSoup
10
+ from sentence_transformers import SentenceTransformer
11
+
12
+ # =====================================================
13
+ # CREATE FOLDERS
14
+ # =====================================================
15
+
16
+ os.makedirs(
17
+ "vector_store",
18
+ exist_ok=True
19
+ )
20
+
21
+ os.makedirs(
22
+ "data/processed",
23
+ exist_ok=True
24
+ )
25
+
26
+ # =====================================================
27
+ # TV SHOW DATABASE
28
+ # =====================================================
29
+
30
+ tv_shows = {
31
+
32
+ "The Blacklist": [
33
+ {
34
+ "season": 1,
35
+ "episode": 1,
36
+ "title": "Pilot",
37
+ "url":
38
+ "https://subslikescript.com/series/The_Blacklist-2741602/season-1/episode-1-Pilot"
39
+ }
40
+ ],
41
+
42
+ "Breaking Bad": [
43
+ {
44
+ "season": 1,
45
+ "episode": 1,
46
+ "title": "Pilot",
47
+ "url":
48
+ "https://subslikescript.com/series/Breaking_Bad-903747/season-1/episode-1-Pilot"
49
+ }
50
+ ],
51
+
52
+ "The Boys": [
53
+ {
54
+ "season": 1,
55
+ "episode": 1,
56
+ "title":
57
+ "The Name of the Game",
58
+
59
+ "url":
60
+ "https://subslikescript.com/series/The_Boys-1190634/season-1/episode-1-The_Name_of_the_Game"
61
+ }
62
+ ]
63
+ }
64
+
65
+ # =====================================================
66
+ # SCRAPE SCRIPT
67
+ # =====================================================
68
+
69
+ def scrape_script(url):
70
+
71
+ try:
72
+
73
+ response = requests.get(
74
+ url,
75
+ headers={
76
+ "User-Agent":
77
+ "Mozilla/5.0"
78
+ },
79
+ timeout=15
80
+ )
81
+
82
+ soup = BeautifulSoup(
83
+ response.text,
84
+ "html.parser"
85
+ )
86
+
87
+ script_div = soup.find(
88
+ "div",
89
+ class_="full-script"
90
+ )
91
+
92
+ if script_div:
93
+
94
+ return script_div.get_text(
95
+ separator="\n"
96
+ )
97
+
98
+ return None
99
+
100
+ except Exception as e:
101
+
102
+ print(
103
+ f"Error scraping {url}"
104
+ )
105
+
106
+ print(e)
107
+
108
+ return None
109
+
110
+
111
+ # =====================================================
112
+ # CLEAN SCRIPT
113
+ # =====================================================
114
+
115
+ def clean_script(raw_text):
116
+
117
+ lines = raw_text.split("\n")
118
+
119
+ cleaned_lines = []
120
+
121
+ dialogue_pattern = re.compile(
122
+ r"^([A-Z\s]+):\s*(.*)"
123
+ )
124
+
125
+ for line in lines:
126
+
127
+ line = line.strip()
128
+
129
+ if not line:
130
+ continue
131
+
132
+ match = dialogue_pattern.match(
133
+ line
134
+ )
135
+
136
+ if match:
137
+
138
+ character = (
139
+ match.group(1)
140
+ .strip()
141
+ )
142
+
143
+ dialogue = (
144
+ match.group(2)
145
+ .strip()
146
+ )
147
+
148
+ cleaned_lines.append(
149
+ f"{character}: {dialogue}"
150
+ )
151
+
152
+ return cleaned_lines
153
+
154
+
155
+ # =====================================================
156
+ # CREATE CHUNKS
157
+ # =====================================================
158
+
159
+ def create_chunks(lines):
160
+
161
+ window_size = 2
162
+
163
+ chunks = []
164
+
165
+ for i in range(len(lines)):
166
+
167
+ start = max(
168
+ 0,
169
+ i - window_size
170
+ )
171
+
172
+ end = min(
173
+ len(lines),
174
+ i + window_size + 1
175
+ )
176
+
177
+ chunk = "\n".join(
178
+ lines[start:end]
179
+ )
180
+
181
+ chunks.append(chunk)
182
+
183
+ return chunks
184
+
185
+
186
+ # =====================================================
187
+ # BUILD DATASET
188
+ # =====================================================
189
+
190
+ all_documents = []
191
+
192
+ for show_name, episodes in tv_shows.items():
193
+
194
+ print(
195
+ f"\nScraping {show_name}"
196
+ )
197
+
198
+ for ep in episodes:
199
+
200
+ raw_text = scrape_script(
201
+ ep["url"]
202
+ )
203
+
204
+ if not raw_text:
205
+ continue
206
+
207
+ lines = clean_script(
208
+ raw_text
209
+ )
210
+
211
+ chunks = create_chunks(
212
+ lines
213
+ )
214
+
215
+ for chunk in chunks:
216
+
217
+ all_documents.append({
218
+
219
+ "series":
220
+ show_name,
221
+
222
+ "season":
223
+ ep["season"],
224
+
225
+ "episode":
226
+ ep["episode"],
227
+
228
+ "title":
229
+ ep["title"],
230
+
231
+ "context":
232
+ chunk
233
+ })
234
+
235
+ # =====================================================
236
+ # DATAFRAME
237
+ # =====================================================
238
+
239
+ df = pd.DataFrame(
240
+ all_documents
241
+ )
242
+
243
+ print(
244
+ f"\nTotal chunks: {len(df)}"
245
+ )
246
+
247
+ df.to_csv(
248
+ "data/processed/shows.csv",
249
+ index=False
250
+ )
251
+
252
+ # =====================================================
253
+ # EMBEDDINGS
254
+ # =====================================================
255
+
256
+ print(
257
+ "\nLoading embedding model..."
258
+ )
259
+
260
+ model = SentenceTransformer(
261
+ "all-MiniLM-L6-v2"
262
+ )
263
+
264
+ texts = df["context"].tolist()
265
+
266
+ embeddings = model.encode(
267
+ texts,
268
+ show_progress_bar=True
269
+ )
270
+
271
+ embeddings = np.array(
272
+ embeddings
273
+ ).astype("float32")
274
+
275
+ # =====================================================
276
+ # FAISS INDEX
277
+ # =====================================================
278
+
279
+ dimension = embeddings.shape[1]
280
+
281
+ index = faiss.IndexFlatL2(
282
+ dimension
283
+ )
284
+
285
+ index.add(
286
+ embeddings
287
+ )
288
+
289
+ # =====================================================
290
+ # SAVE VECTOR DB
291
+ # =====================================================
292
+
293
+ faiss.write_index(
294
+ index,
295
+ "vector_store/faiss_index.bin"
296
+ )
297
+
298
+ with open(
299
+ "vector_store/metadata.pkl",
300
+ "wb"
301
+ ) as f:
302
+
303
+ pickle.dump(
304
+ all_documents,
305
+ f
306
+ )
307
+
308
+ print(
309
+ "\n✅ Entertainment database built successfully!"
310
+ )