tomasruiz commited on
Commit
32b48a8
·
verified ·
1 Parent(s): 7e9d324

Upload 3 files

Browse files

Added hydration script, requirement.txt file, and README.md file describing how to run the code

Files changed (3) hide show
  1. README.md +23 -15
  2. hydrate.py +434 -0
  3. requirements.txt +2 -0
README.md CHANGED
@@ -1,15 +1,23 @@
1
- ---
2
- license: apache-2.0
3
- task_categories:
4
- - video-classification
5
- - image-classification
6
- language:
7
- - de
8
- - en
9
- tags:
10
- - tiktok
11
- - video
12
- - social_media
13
- size_categories:
14
- - 100K<n<1M
15
- ---
 
 
 
 
 
 
 
 
 
1
+ # Politok-DE Hydration Code
2
+
3
+ The script `hydrate.py` must be in the same directory as the `politok-de.parquet` file.
4
+ It will scrape the posts from the TikTok Website, and create for each post:
5
+
6
+ 1. A video or image + audio file in the `media/` directory.
7
+ 2. An entry entry in the `media_progress.csv` file, stating if the post was successfully scraped.
8
+ 3. An entry with post metadata in the `media_metadata.csv` file, only if the post was successfully scraped.
9
+
10
+ Install dependencies:
11
+
12
+ ```shel
13
+ pip install -r requirements.txt
14
+ ```
15
+
16
+ Run the script:
17
+
18
+ ```shell
19
+ python hydrate.py
20
+ ```
21
+
22
+ Note: To interrupt the script, you might need to press `Ctrl+C` multiple times.
23
+ I think its related to the concurrent nature of the scraping code.
hydrate.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from concurrent.futures import ThreadPoolExecutor, as_completed
2
+ from dataclasses import asdict, dataclass, field, replace
3
+ from logging import getLogger
4
+ import logging
5
+ from pathlib import Path
6
+ import time
7
+ import random
8
+ from typing import Any, Callable, Generic, Literal, TypeVar
9
+ from decorator import decorator
10
+ import pyktok as pyk
11
+ import pandas as pd
12
+ import requests
13
+ from tenacity import retry, stop_after_attempt, wait_random
14
+ import tenacity
15
+
16
+ logger = getLogger(__name__)
17
+
18
+
19
+ def main():
20
+ configure_logging()
21
+ target_paths = FilePaths(
22
+ media_dir=Path("./media"),
23
+ media_progress_csv=Path("./media_progress.csv"),
24
+ media_metadata_csv=Path("./media_metadata.csv"),
25
+ )
26
+ df = pd.read_parquet("./politok-de.parquet")
27
+ posts = [Post(content_id=id) for id in df["video_id"]]
28
+ download_post_in_parallel(tgt_paths=target_paths, posts=posts)
29
+
30
+
31
+ def configure_logging(logfile: Path | None = None, level: int = logging.INFO) -> None:
32
+ fmt = "%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(message)s"
33
+ if logfile is not None:
34
+ print("Redirecting logs to file: %s" % logfile)
35
+ logging.basicConfig(level=level, format=fmt, filename=logfile, force=True)
36
+
37
+
38
+ @decorator
39
+ def safely(
40
+ f: Callable,
41
+ quiet: bool = False,
42
+ notify: bool = False,
43
+ metadata: dict = {},
44
+ *args,
45
+ **kwargs,
46
+ ):
47
+ """
48
+ Will catch any exception thrown by the function and return a Result object.
49
+ metadata is a dictionary that will be sent to bugsnag if notify is True.
50
+ """
51
+ try:
52
+ result = Result.from_value(f(*args, **kwargs))
53
+ except Exception as e:
54
+ if not quiet:
55
+ logger.error("Exception running function '%s' safely", f.__name__)
56
+ logger.exception(e)
57
+ if notify:
58
+ pass # bugsnag logic
59
+ result = Result.from_error(unpack(e))
60
+ return result.flatten()
61
+
62
+
63
+ def unpack(e: Exception) -> Exception:
64
+ """Unpacking is needed when a wrapping exception is non-informative"""
65
+ if isinstance(e, tenacity.RetryError):
66
+ return e.last_attempt.exception()
67
+ return e
68
+
69
+
70
+ @dataclass
71
+ class Post:
72
+ content_id: str
73
+ author: str = "placeholder"
74
+
75
+ def post_url(self, type_: Literal["video", "photo"]) -> str:
76
+ return f"https://www.tiktok.com/@{self.author}/{type_}/{self.content_id}"
77
+
78
+ def local_video_filename(self) -> str:
79
+ return f"video_{self.content_id}.mp4"
80
+
81
+ def local_audio_filename(self) -> str:
82
+ return f"audio_{self.content_id}.mp3"
83
+
84
+ def local_imgs_filenames(self, n_imgs: int) -> list[str]:
85
+ return [f"img_{self.content_id}_{i}.jpg" for i in range(1, n_imgs + 1)]
86
+
87
+
88
+ @dataclass
89
+ class DownloadReq:
90
+ """Request to download a video"""
91
+
92
+ post: Post
93
+ paths: "FilePaths"
94
+ hydrate_media: bool = True
95
+
96
+
97
+ @dataclass
98
+ class ImgPostInfo:
99
+ imgs: list[bytes]
100
+ data_row: pd.DataFrame
101
+ audio: bytes | None
102
+
103
+
104
+ class PostUnretrievable(Exception):
105
+ pass
106
+
107
+
108
+ class FilePaths:
109
+ def __init__(
110
+ self, media_dir: Path, media_progress_csv: Path, media_metadata_csv: Path
111
+ ):
112
+ self._media_dir = media_dir
113
+ self._media_progress_csv = media_progress_csv
114
+ self._media_metadata_csv = media_metadata_csv
115
+
116
+ def media_dir(self) -> Path:
117
+ return self._media_dir
118
+
119
+ def media_progress_csv(self) -> Path:
120
+ return self._media_progress_csv
121
+
122
+ def media_metadata_csv(self) -> Path:
123
+ return self._media_metadata_csv
124
+
125
+
126
+ def download_post_in_parallel(
127
+ tgt_paths: FilePaths, posts: list[Post], hydrate_media=True
128
+ ):
129
+ if len(posts) == 0:
130
+ logger.info("Passed 0 posts to download.")
131
+ return
132
+
133
+ completed = 0
134
+ errored = 0
135
+ iter = (
136
+ DownloadReq(post=p, paths=tgt_paths, hydrate_media=hydrate_media) for p in posts
137
+ )
138
+
139
+ n_threads = min(10, len(posts))
140
+ logger.info(
141
+ "Concurrently downloading %d posts using %d threads.", len(posts), n_threads
142
+ )
143
+ # Using threads rather than processes because the workload is IO-bound, not CPU-bound
144
+ with ThreadPoolExecutor(max_workers=n_threads) as executor:
145
+ futures = [executor.submit(wait_and_download_post, req) for req in iter]
146
+ for idx, future in enumerate(as_completed(futures)):
147
+ result = future.result()
148
+ if not result.success:
149
+ errored += 1
150
+ completed += 1
151
+ logger.info(
152
+ f"Completed {completed} out of {len(posts)} posts."
153
+ f" CompletePct={idx / len(posts):.2%}."
154
+ f" ErrorPct={errored / completed:.2%}"
155
+ )
156
+ df = _mk_media_progress_df(result=result)
157
+ append_df_to_file(df, tgt_paths.media_progress_csv(), quiet=True)
158
+
159
+
160
+ @dataclass
161
+ class MediaProgressEntry:
162
+ post_video_url: str
163
+ success: bool
164
+ error_dict_as_str: str
165
+ timestamp: pd.Timestamp = field(default_factory=pd.Timestamp.now)
166
+
167
+
168
+ def _mk_media_progress_df(result: "Result[Post]") -> pd.DataFrame:
169
+ post = result.info
170
+ assert isinstance(post, Post)
171
+ entry = MediaProgressEntry(
172
+ post_video_url=post.post_url("video"),
173
+ success=result.success,
174
+ error_dict_as_str="" if result.success else str(result.error),
175
+ )
176
+ df = pd.DataFrame(asdict(entry), index=pd.Index([0]))
177
+ return df[["timestamp", "success", "post_video_url", "error_dict_as_str"]]
178
+
179
+
180
+ def wait_and_download_post(req: DownloadReq) -> "Result[Post]":
181
+ time.sleep(random.random() * 0.5) # random delay of 0 to 0.5s
182
+ return download_post(req=req)
183
+
184
+
185
+ def download_post(req: DownloadReq) -> "Result[Post]":
186
+ post = req.post
187
+ vresult: Result[bool] = safely(download_video, quiet=True)(req=req)
188
+ if vresult.success:
189
+ return vresult.with_info(info=post)
190
+
191
+ post_is_not_retrievable: bool = PostUnretrievable.__name__ in vresult.error
192
+ fail_msg = "Failed to download post with content_id=%s. Skipping. Error: %s"
193
+ if post_is_not_retrievable:
194
+ logger.error(fail_msg, post.content_id, repr(vresult.error))
195
+ return vresult.with_info(info=post)
196
+
197
+ msg = (
198
+ "Failed to download post with content_id=%s as video. Trying as imgs. Error: %s"
199
+ )
200
+ logger.info(msg, post.content_id, repr(vresult.error))
201
+ im_result: Result = safely(download_imgs_post, quiet=True)(req=req)
202
+ if not im_result.success:
203
+ logger.error(fail_msg, post.content_id, repr(vresult.error))
204
+ return im_result.with_info(info=post)
205
+
206
+
207
+ def download_imgs_post(req: DownloadReq) -> "Result[ImgPostInfo]":
208
+ if not req.hydrate_media:
209
+ data_row = _extract_data_row(get_tiktok_json(req.post))
210
+ dump_data_row(data_row=data_row, paths=req.paths)
211
+ img_post_info = ImgPostInfo(imgs=[], data_row=data_row, audio=None)
212
+ return Result.from_value(value=img_post_info)
213
+
214
+ result: Result[ImgPostInfo] = fetch_img_post_info(p=req.post)
215
+ if not result.success:
216
+ return result # type: ignore
217
+ info = result.value
218
+ assert isinstance(info, ImgPostInfo)
219
+ dump_post_media(p=req.post, info=info, paths=req.paths)
220
+ return result
221
+
222
+
223
+ def dump_post_media(p: Post, info: ImgPostInfo, paths: FilePaths) -> None:
224
+ imgs: list[bytes] = info.imgs
225
+ imgs_filenames = p.local_imgs_filenames(n_imgs=len(imgs))
226
+ for img, filename in zip(imgs, imgs_filenames):
227
+ img_path = paths.media_dir() / filename
228
+ img_path.write_bytes(img)
229
+ logger.debug("Saved img to '%s'", img_path.absolute())
230
+
231
+ if info.audio is not None:
232
+ audio_path = paths.media_dir() / p.local_audio_filename()
233
+ audio_path.write_bytes(info.audio)
234
+ logger.debug("Saved audio to '%s'", audio_path.absolute())
235
+
236
+ dump_data_row(data_row=info.data_row, paths=paths)
237
+
238
+
239
+ @safely(quiet=True)
240
+ def fetch_img_post_info(p: Post) -> ImgPostInfo:
241
+ tt_json: dict = get_tiktok_json(p)
242
+ fail_if_unretrievable(tt_json)
243
+ data_row: pd.DataFrame = _extract_data_row(tt_json)
244
+ urls: list[str] = _extract_imgs_urls(tt_json)
245
+ logger.debug(
246
+ "For post author=%s, id=%s, found num_imgs=%d",
247
+ p.author,
248
+ p.content_id,
249
+ len(urls),
250
+ )
251
+ imgs: list[bytes] = [fetch_content(url) for url in urls]
252
+
253
+ audio_url = _extract_audio_url(tt_json)
254
+ if audio_url == "":
255
+ audio = None
256
+ else:
257
+ audio: bytes = fetch_content(audio_url)
258
+
259
+ info = ImgPostInfo(imgs=imgs, audio=audio, data_row=data_row)
260
+ return info
261
+
262
+
263
+ def dump_data_row(data_row: pd.DataFrame, paths: FilePaths) -> None:
264
+ return append_df_to_file(data_row, paths.media_metadata_csv(), quiet=True)
265
+
266
+
267
+ def _extract_data_row(tt_json: dict) -> pd.DataFrame:
268
+ data: dict = data_slot(tt_json)
269
+ data_row: pd.DataFrame = pyk.generate_data_row(data)
270
+ return data_row
271
+
272
+
273
+ def _extract_audio_url(tt_json: dict) -> str:
274
+ data: dict = data_slot(tt_json)
275
+ return data["music"]["playUrl"]
276
+
277
+
278
+ def _extract_imgs_urls(tt_json: dict) -> list[str]:
279
+ data: dict = data_slot(tt_json)
280
+ imgs: list[dict] = data["imagePost"]["images"]
281
+ return [img["imageURL"]["urlList"][0] for img in imgs]
282
+
283
+
284
+ def data_slot(tt_json: dict) -> dict:
285
+ detail: dict = tt_json["__DEFAULT_SCOPE__"]["webapp.video-detail"]
286
+ return detail["itemInfo"]["itemStruct"]
287
+
288
+
289
+ def get_tiktok_json(p: Post) -> dict:
290
+ return get_tiktok_json_from_url(video_url=p.post_url("video"))
291
+
292
+
293
+ def get_tiktok_json_from_url(video_url: str) -> dict:
294
+ tt_json = pyk.alt_get_tiktok_json(video_url=video_url)
295
+ if tt_json is None:
296
+ raise PostUnretrievable("pyktok.alt_get_tiktok_json returned None")
297
+ return tt_json
298
+
299
+
300
+ def fail_if_unretrievable(tt_json: dict) -> None:
301
+ msg = status_msg(tt_json)
302
+ if msg == "status_friend_see":
303
+ emsg = f"Post is presumably only visible to the author's friends: statusMsg='{msg}'"
304
+ raise PostUnretrievable(emsg)
305
+ if msg == "cross_border_violation":
306
+ raise PostUnretrievable(
307
+ f"This video isn't available in your country or region: statusMsg='{msg}'"
308
+ )
309
+ if msg == "status_self_see":
310
+ emsg = f"Post is presumably only visible to the author: statusMsg='{msg}'"
311
+ raise PostUnretrievable(emsg)
312
+ if msg == "item doesn't exist":
313
+ emsg = "Video currently unavailable. Post or user might have been deleted."
314
+ raise PostUnretrievable(emsg)
315
+ if msg == "author_secret":
316
+ emsg = "Account is private. Only approved users can view content."
317
+ raise PostUnretrievable(emsg)
318
+ if msg == "status_deleted":
319
+ raise PostUnretrievable(f"Post was deleted. StatusMsg='{msg}'")
320
+ if msg != "ok" and msg != "":
321
+ raise PostUnretrievable(f"Unknown status message: '{msg}'")
322
+ if is_content_classified(tt_json): # this line requires checking 'itemInfo'
323
+ emsg = "Content is classified. User must be logged in to watch."
324
+ raise PostUnretrievable(emsg)
325
+
326
+
327
+ def is_content_classified(tt_json: dict) -> bool:
328
+ key = "isContentClassified"
329
+ container = tt_json["__DEFAULT_SCOPE__"]["webapp.video-detail"]["itemInfo"][
330
+ "itemStruct"
331
+ ]
332
+ return key in container and container[key]
333
+
334
+
335
+ def status_msg(tt_json: dict) -> str:
336
+ return tt_json["__DEFAULT_SCOPE__"]["webapp.video-detail"]["statusMsg"]
337
+
338
+
339
+ def download_video(req: DownloadReq) -> None:
340
+ post = req.post
341
+ paths = req.paths
342
+ """Downloads he video without TikTok watermarks"""
343
+ tt_json = get_tiktok_json(p=post)
344
+ fail_if_unretrievable(tt_json)
345
+ data_row: pd.DataFrame = _extract_data_row(tt_json)
346
+ if req.hydrate_media:
347
+ video: bytes = fetch_content(_extract_video_url(tt_json))
348
+ video_path = paths.media_dir() / post.local_video_filename()
349
+ video_path.parent.mkdir(parents=True, exist_ok=True)
350
+ video_path.write_bytes(video)
351
+ logger.debug("Saved video to '%s'", video_path.absolute())
352
+
353
+ # only append the metadata if no error was raised before
354
+ append_df_to_file(df=data_row, path=paths.media_metadata_csv(), quiet=True)
355
+
356
+
357
+ def _extract_video_url(tt_json: dict) -> str:
358
+ url: str | None = data_slot(tt_json)["video"]["playAddr"]
359
+ if url is None or url == "":
360
+ msg = "Video url is None or empty string."
361
+ raise ValueError(msg)
362
+ return url
363
+
364
+
365
+ @retry(stop=stop_after_attempt(2), wait=wait_random(min=1, max=2))
366
+ def fetch_content(url: str) -> bytes:
367
+ logger.debug("Fetching Content from: %s", url)
368
+ headers = pyk.headers | dict(referer="https://www.tiktok.com/")
369
+ from pyktok.pyktok import cookies
370
+
371
+ # proxy: dict = random.choice(load_listof_proxies_for_requests())
372
+ response = requests.get(url, headers=headers, cookies=cookies, timeout=30)
373
+ response.raise_for_status()
374
+ return response.content
375
+
376
+
377
+ def append_df_to_file(
378
+ df: pd.DataFrame, path: Path, quiet: bool = False, jsonl: bool = False
379
+ ) -> None:
380
+ if len(df) == 0:
381
+ logger.info("df is empty, no rows to append to file")
382
+ return
383
+
384
+ data_dir = path.parent
385
+ data_dir.mkdir(parents=True, exist_ok=True)
386
+ if jsonl:
387
+ df_to_jsonl(df, path)
388
+ else:
389
+ df.to_csv(path, mode="a", header=not path.exists(), index=False)
390
+ if not quiet:
391
+ logger.info(f"Appended {len(df)} rows to '{path.absolute()}'")
392
+
393
+
394
+ def df_to_jsonl(df: pd.DataFrame, path: Path, mode="a") -> None:
395
+ df.to_json(path, lines=True, mode=mode, orient="records")
396
+
397
+
398
+ T = TypeVar("T")
399
+
400
+
401
+ @dataclass(frozen=True)
402
+ class Result(Generic[T]):
403
+ # TODO: success should be a computed value
404
+ success: bool
405
+ """Excatly one of value or error should be None"""
406
+ value: T | None
407
+ error: str | None
408
+
409
+ """info is optinal and can be used to include more information about the result"""
410
+ info: Any | None = None
411
+
412
+ @classmethod
413
+ def from_value(cls, val: T, info=None):
414
+ return cls(success=True, value=val, error=None, info=info)
415
+
416
+ @classmethod
417
+ def from_error(cls, err: Exception | str, info=None):
418
+ error_str = repr(err) if isinstance(err, Exception) else err
419
+ return cls(success=False, value=None, error=error_str, info=info)
420
+
421
+ def flatten(self):
422
+ if not self.success:
423
+ return self
424
+ if isinstance(self.value, Result):
425
+ return self.value.flatten() # type: ignore
426
+ else:
427
+ return self
428
+
429
+ def with_info(self, info: Any | None):
430
+ return replace(self, info=info)
431
+
432
+
433
+ if __name__ == "__main__":
434
+ main()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ decorator
2
+ pyktok