d0rj commited on
Commit
ea7f3ab
·
verified ·
1 Parent(s): 9653e68

Add 2345 Telegram meme posts through 9102

Browse files

Preserve 6239 existing rows and schema; include source provenance, audit and resumable scraper.

README.md CHANGED
@@ -1,43 +1,53 @@
1
- ---
2
- dataset_info:
3
- features:
4
- - name: id
5
- dtype: int64
6
- - name: description
7
- dtype: string
8
- - name: photos
9
- large_list: image
10
- splits:
11
- - name: train
12
- num_bytes: 403295816
13
- num_examples: 6239
14
- download_size: 399709915
15
- dataset_size: 403295816
16
- configs:
17
- - config_name: default
18
- data_files:
19
- - split: train
20
- path: data/train-*
21
- license: apache-2.0
22
- task_categories:
23
- - image-to-text
24
- - visual-question-answering
25
- language:
26
- - ru
27
- multilinguality:
28
- - monolingual
29
- tags:
30
- - meme
31
- - captions
32
- - sft
33
- - qa
34
- ---
35
-
36
- # text_meme
37
-
38
- Соскрапено с отличного Telegram канала [текстовые мемы](https://t.me/text_meme).
39
-
40
- ## Dataset Description
41
-
42
- - **Homepage** https://t.me/text_meme
43
- - **Homepage** https://vk.com/textmeme
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ dataset_info:
3
+ features:
4
+ - name: id
5
+ dtype: int64
6
+ - name: description
7
+ dtype: string
8
+ - name: photos
9
+ large_list: image
10
+ splits:
11
+ - name: train
12
+ num_bytes: 601100938
13
+ num_examples: 8584
14
+ download_size: 595690535
15
+ dataset_size: 601100938
16
+ configs:
17
+ - config_name: default
18
+ data_files:
19
+ - split: train
20
+ path: data/train-*
21
+ license: apache-2.0
22
+ task_categories:
23
+ - image-to-text
24
+ - visual-question-answering
25
+ language:
26
+ - ru
27
+ multilinguality:
28
+ - monolingual
29
+ tags:
30
+ - meme
31
+ - captions
32
+ - sft
33
+ - qa
34
+ ---
35
+
36
+ # text_meme
37
+
38
+ Соскрапено с отличного Telegram канала [текстовые мемы](https://t.me/text_meme).
39
+
40
+ ## Dataset Description
41
+
42
+ - **Homepage** https://t.me/text_meme
43
+ - **Homepage** https://vk.com/textmeme
44
+
45
+ ## Incremental update 2026-10-15
46
+
47
+ Added **2,345** posts (**2,345** images) from [the public Telegram channel](https://t.me/text_meme); train now has **8,584** rows. New post IDs: 6446–9102; dates: 2025-03-13T07:46:38+00:00 to 2026-10-15T11:12:37+00:00.
48
+
49
+ The existing Parquet files and examples are preserved. Schema remains `id`, `description`, `photos` (a large list of embedded images). Descriptions are channel annotations, with HTML formatting removed and line breaks preserved. New images are Telegram public web previews; their resolution may differ from original Telegram files. Posts require both a nonempty description and at least one valid photo. Deduplication uses Telegram post IDs; reposted images with distinct annotations are retained.
50
+
51
+ Excluded 15 posts without text/photos; deferred 4 posts with unavailable media ([retry inventory](deferred.jsonl)). The crawl reached the previous maximum message ID 6445. Deleted/unavailable posts, older gaps, and future posts are outside this update. See [audit](audit.json) for exclusions, counts, hashes and coverage, and [provenance](provenance.jsonl) for source URLs, timestamps and image hashes. The scraper and its tests are in [scraper](scraper/README.md).
52
+
53
+ The repository's existing Apache-2.0 metadata is retained. This does not establish ownership or permissions for third-party meme images and underlying works.
audit.json ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repo": "d0rj/text_meme",
3
+ "baseline_revision": "9653e689a74768a4a5d4b3d3a7165dc40ed9c804",
4
+ "generated_at": "2026-10-15T11:31:00.625651+00:00",
5
+ "baseline_rows": 6239,
6
+ "added_rows": 2345,
7
+ "total_rows": 8584,
8
+ "new_id_min": 6446,
9
+ "new_id_max": 9102,
10
+ "published_at_min": "2025-03-13T07:46:38+00:00",
11
+ "published_at_max": "2026-10-15T11:12:37+00:00",
12
+ "new_images": 2345,
13
+ "schema_preserved": true,
14
+ "new_data_num_bytes": 197805122,
15
+ "new_parquet": {
16
+ "path": "data/train-update-00006446-00009102.parquet",
17
+ "sha256": "33079084c39432f7052e9c8d87ecaccc357d478142c38c180a2b20ddfb8b1897",
18
+ "bytes": 195980620
19
+ },
20
+ "baseline_files": [
21
+ {
22
+ "path": "data/train-00000-of-00001.parquet",
23
+ "sha256": "671412b3df1f6f1318613840dc9e9907f132ba4f948996031bd7ca7dda404a3a",
24
+ "bytes": 399709915
25
+ }
26
+ ],
27
+ "crawl": {
28
+ "started_at": "2026-10-15T11:22:15.324380+00:00",
29
+ "since_id": 6445,
30
+ "upper_id": 9102,
31
+ "cursor": 6430,
32
+ "complete": true,
33
+ "pages": 119,
34
+ "updated_at": "2026-10-15T11:23:47.719283+00:00"
35
+ },
36
+ "status_counts": {
37
+ "deferred": 4,
38
+ "excluded": 15,
39
+ "ready": 2345
40
+ },
41
+ "excluded": [
42
+ {
43
+ "id": 6509,
44
+ "reason": "no_photos"
45
+ },
46
+ {
47
+ "id": 6511,
48
+ "reason": "no_photos"
49
+ },
50
+ {
51
+ "id": 6577,
52
+ "reason": "no_photos"
53
+ },
54
+ {
55
+ "id": 6602,
56
+ "reason": "no_photos"
57
+ },
58
+ {
59
+ "id": 6750,
60
+ "reason": "no_photos"
61
+ },
62
+ {
63
+ "id": 6785,
64
+ "reason": "no_photos"
65
+ },
66
+ {
67
+ "id": 6998,
68
+ "reason": "no_photos"
69
+ },
70
+ {
71
+ "id": 7269,
72
+ "reason": "no_photos"
73
+ },
74
+ {
75
+ "id": 7530,
76
+ "reason": "no_photos"
77
+ },
78
+ {
79
+ "id": 7685,
80
+ "reason": "no_photos"
81
+ },
82
+ {
83
+ "id": 7847,
84
+ "reason": "no_photos"
85
+ },
86
+ {
87
+ "id": 7903,
88
+ "reason": "no_photos"
89
+ },
90
+ {
91
+ "id": 8233,
92
+ "reason": "no_photos"
93
+ },
94
+ {
95
+ "id": 8422,
96
+ "reason": "no_photos"
97
+ },
98
+ {
99
+ "id": 9101,
100
+ "reason": "no_description"
101
+ }
102
+ ],
103
+ "unobserved_message_ids": [
104
+ 7191,
105
+ 7201,
106
+ 7203,
107
+ 7205,
108
+ 7219,
109
+ 7223,
110
+ 7234,
111
+ 7236,
112
+ 7244,
113
+ 7250,
114
+ 7256,
115
+ 7270,
116
+ 7275,
117
+ 7278,
118
+ 7279,
119
+ 7280,
120
+ 7281,
121
+ 7282,
122
+ 7283,
123
+ 7290,
124
+ 7304,
125
+ 7318,
126
+ 7320,
127
+ 7321,
128
+ 7322,
129
+ 7323,
130
+ 7324,
131
+ 7325,
132
+ 7326,
133
+ 7327,
134
+ 7338,
135
+ 7341,
136
+ 7343,
137
+ 7355,
138
+ 7359,
139
+ 7372,
140
+ 7376,
141
+ 7377,
142
+ 7378,
143
+ 7379,
144
+ 7380,
145
+ 7389,
146
+ 7393,
147
+ 7396,
148
+ 7402,
149
+ 7406,
150
+ 7407,
151
+ 7408,
152
+ 7409,
153
+ 7410,
154
+ 7411,
155
+ 7412,
156
+ 7413,
157
+ 7414,
158
+ 7415,
159
+ 7433,
160
+ 7442,
161
+ 7448,
162
+ 7451,
163
+ 7453,
164
+ 7455,
165
+ 7471,
166
+ 7474,
167
+ 7476,
168
+ 7478,
169
+ 7480,
170
+ 7482,
171
+ 7484,
172
+ 7486,
173
+ 7489,
174
+ 7493,
175
+ 7518,
176
+ 7520,
177
+ 7531,
178
+ 7534,
179
+ 7538,
180
+ 7539,
181
+ 7540,
182
+ 7541,
183
+ 7542,
184
+ 7545,
185
+ 7551,
186
+ 7552,
187
+ 7553,
188
+ 7555,
189
+ 7561,
190
+ 7579,
191
+ 7585,
192
+ 7588,
193
+ 7593,
194
+ 7595,
195
+ 7599,
196
+ 7609,
197
+ 7613,
198
+ 7630,
199
+ 7632,
200
+ 7634,
201
+ 7638,
202
+ 7652,
203
+ 7659,
204
+ 7670,
205
+ 7681,
206
+ 7693,
207
+ 7704,
208
+ 7722,
209
+ 7729,
210
+ 7730,
211
+ 7731,
212
+ 7735,
213
+ 7736,
214
+ 7752,
215
+ 7774,
216
+ 7777,
217
+ 7782,
218
+ 7790,
219
+ 7798,
220
+ 7802,
221
+ 7824,
222
+ 7830,
223
+ 7842,
224
+ 7860,
225
+ 7863,
226
+ 7873,
227
+ 7884,
228
+ 7899,
229
+ 7902,
230
+ 7913,
231
+ 7914,
232
+ 7915,
233
+ 7916,
234
+ 7917,
235
+ 7920,
236
+ 7932,
237
+ 7937,
238
+ 7950,
239
+ 7953,
240
+ 7985,
241
+ 7992,
242
+ 7994,
243
+ 7995,
244
+ 8011,
245
+ 8013,
246
+ 8019,
247
+ 8027,
248
+ 8032,
249
+ 8036,
250
+ 8061,
251
+ 8075,
252
+ 8083,
253
+ 8096,
254
+ 8100,
255
+ 8112,
256
+ 8122,
257
+ 8127,
258
+ 8135,
259
+ 8140,
260
+ 8149,
261
+ 8162,
262
+ 8165,
263
+ 8171,
264
+ 8174,
265
+ 8175,
266
+ 8186,
267
+ 8203,
268
+ 8207,
269
+ 8224,
270
+ 8230,
271
+ 8237,
272
+ 8242,
273
+ 8259,
274
+ 8270,
275
+ 8272,
276
+ 8275,
277
+ 8291,
278
+ 8297,
279
+ 8299,
280
+ 8305,
281
+ 8309,
282
+ 8311,
283
+ 8312,
284
+ 8315,
285
+ 8321,
286
+ 8323,
287
+ 8342,
288
+ 8344,
289
+ 8359,
290
+ 8361,
291
+ 8392,
292
+ 8394,
293
+ 8403,
294
+ 8404,
295
+ 8405,
296
+ 8425,
297
+ 8431,
298
+ 8435,
299
+ 8446,
300
+ 8452,
301
+ 8456,
302
+ 8469,
303
+ 8474,
304
+ 8477,
305
+ 8490,
306
+ 8491,
307
+ 8492,
308
+ 8493,
309
+ 8494,
310
+ 8561,
311
+ 8563,
312
+ 8567,
313
+ 8575,
314
+ 8592,
315
+ 8596,
316
+ 8603,
317
+ 8607,
318
+ 8610,
319
+ 8616,
320
+ 8624,
321
+ 8629,
322
+ 8632,
323
+ 8633,
324
+ 8638,
325
+ 8643,
326
+ 8645,
327
+ 8650,
328
+ 8657,
329
+ 8658,
330
+ 8660,
331
+ 8664,
332
+ 8665,
333
+ 8666,
334
+ 8667,
335
+ 8668,
336
+ 8669,
337
+ 8670,
338
+ 8671,
339
+ 8672,
340
+ 8673,
341
+ 8680,
342
+ 8686,
343
+ 8702,
344
+ 8703,
345
+ 8704,
346
+ 8712,
347
+ 8717,
348
+ 8721,
349
+ 8725,
350
+ 8739,
351
+ 8743,
352
+ 8745,
353
+ 8749,
354
+ 8760,
355
+ 8778,
356
+ 8785,
357
+ 8791,
358
+ 8798,
359
+ 8803,
360
+ 8804,
361
+ 8808,
362
+ 8809,
363
+ 8810,
364
+ 8811,
365
+ 8812,
366
+ 8822,
367
+ 8846,
368
+ 8848,
369
+ 8859,
370
+ 8878,
371
+ 8892,
372
+ 8897,
373
+ 8898,
374
+ 8899,
375
+ 8900,
376
+ 8901,
377
+ 8911,
378
+ 8912,
379
+ 8913,
380
+ 8914,
381
+ 8919,
382
+ 8939,
383
+ 8940,
384
+ 8941,
385
+ 8942,
386
+ 8943,
387
+ 8953,
388
+ 8956,
389
+ 8981,
390
+ 8997,
391
+ 9043,
392
+ 9044,
393
+ 9045,
394
+ 9049,
395
+ 9056,
396
+ 9060
397
+ ],
398
+ "deferred_media_ids": [
399
+ 6571,
400
+ 6720,
401
+ 7064,
402
+ 7298
403
+ ],
404
+ "exact_image_duplicate_groups_within_update": [],
405
+ "exact_image_matches_to_baseline": [],
406
+ "preserved_legacy_missing_description_ids": [
407
+ 622
408
+ ],
409
+ "dedup_policy": "Unique Telegram post ID; identical images in distinct annotated posts retained.",
410
+ "coverage": "Public HTML posts above baseline max ID through frozen first-page upper ID. Deleted/unavailable IDs and older holes are not recovered.",
411
+ "image_source": "Telegram public web preview JPEGs; original-resolution Telegram API files are not claimed."
412
+ }
data/train-update-00006446-00009102.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33079084c39432f7052e9c8d87ecaccc357d478142c38c180a2b20ddfb8b1897
3
+ size 195980620
deferred.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"id": 6571, "description": "На сером фоне расположено неестественно вытянутое лицо гуманоидного существа с бледно-серой кожей. Существо известно под названием «Locked In Alien (Сосредоточенный пришелец)». Взгляд своих затемнённых глазниц оно устремило на читателя мема.\nСнизу текст: \n«четырёхлетний я, когда рандомно одним вечером обрёл самосознание».", "photo_urls": ["https://cdn4.telesco.pe/file/UBX6pEQvW3H-XGubTzGIMJ9WQWzr37tLjBURpXsqWz_srd4_dURN6PazfyAg3F2bd4oQmaK5zDj0usBM5sOBpRW2QqiEXlajFR7ZBBmUrBpApTChGB5FcrsowY-k63Ib7DbVlOsr319CyU8YP0nr-pJa0R_jUoCQKJ5aPi21xB-00DETPmvLHRSgUZJslBUYbDb-2yXVpUzXEcxh4AuXoSWB32eC6H9HMWHp57iJXNrejbmPi2nUfGIgI2KXyYn95Eh3xl54tyAI-NgJbbAnCdPrnTH377QwdpWemxyPRyHKpU9uMDXp3k6Yazn52FGAOU1kqagat6GF2WMjD9nhiw.jpg"], "source_url": "https://t.me/text_meme/6571", "published_at": "2025-04-13T11:36:29+00:00", "page_sha256": "2a05cdc7be3338de4c25fc7289ef13d86bc30f1f9fca874a1b59b337d3839163", "fetched_at": "2026-10-15T11:23:42.396394+00:00", "reason": "RetryError: HTTPSConnectionPool(host='cdn4.telesco.pe', port=443): Max retries exceeded with url: /file/UBX6pEQvW3H-XGubTzGIMJ9WQWzr37tLjBURpXsqWz_srd4_dURN6PazfyAg3F2bd4oQmaK5zDj0usBM5sOBpRW2QqiEXlajFR7ZBBmUrBpApTChGB5FcrsowY-k63Ib7DbVlOsr319CyU8YP0nr-pJa0R_jUoCQKJ5aPi21xB-00DETPmvLHRSgUZJslBUYbDb-2yXVpUzXEcxh4AuXoSWB32eC6H9HMWHp57iJXNrejbmPi2nUfGIgI2KXyYn95Eh3xl54tyAI-NgJbbAnCdPrnTH377QwdpWemxyPRyHKpU9uMDXp3k6Yazn52FGAOU1kqagat6GF2WMjD9nhiw.jpg (Caused by ResponseError('too many 500 error responses'))"}
2
+ {"id": 6720, "description": "На заднем плане мема представлено изображение, сгенерированное с помощью нейросети. На нём изображён банан с лицом человека, очищенный наполовину. Банан хмуро и серьёзно смотрит на читателя мема. Текст посередине картинки:\n\"когда препод спросил твою фамилию, а у тебя не грузит чат gpt\".", "photo_urls": ["https://cdn4.telesco.pe/file/m7kbI7EsZKr4l77kf_ENjOez72Zio7vHnz8RtXyTHI5x2MLlXDwZGjYImJBG8ZHOvsYx5jxW7Qo0O5Ni0binQAhrMXeNxqe12E67gC5bKMtJ10U6BMTc1pHnQDCTtE3Xhkl5h7lFAexN87dLvM26tEMrcFa8jOe7Ya7-_0Y2AMkIz_9U6XcZwEPKNt9RkhFOUtMpdB3fPskYK2uoXSGSRKq61Qe_9YzdB0CxWguLoGLot5SUm_db_SHd_tzt2hZ3vxz-Q1I3dVFdEypkRovE12EZBUaUc8fkUOdP9IzuuDtyzT23MXFjfZJOEjJOGn7_fMjP0Ozo5VlqN4hDo02glQ.jpg"], "source_url": "https://t.me/text_meme/6720", "published_at": "2025-05-22T07:50:44+00:00", "page_sha256": "b179686aeafce0342da92a026f301d31e47104cce85e81b6ddb2d8131e5ef862", "fetched_at": "2026-10-15T11:23:36.915524+00:00", "reason": "RetryError: HTTPSConnectionPool(host='cdn4.telesco.pe', port=443): Max retries exceeded with url: /file/m7kbI7EsZKr4l77kf_ENjOez72Zio7vHnz8RtXyTHI5x2MLlXDwZGjYImJBG8ZHOvsYx5jxW7Qo0O5Ni0binQAhrMXeNxqe12E67gC5bKMtJ10U6BMTc1pHnQDCTtE3Xhkl5h7lFAexN87dLvM26tEMrcFa8jOe7Ya7-_0Y2AMkIz_9U6XcZwEPKNt9RkhFOUtMpdB3fPskYK2uoXSGSRKq61Qe_9YzdB0CxWguLoGLot5SUm_db_SHd_tzt2hZ3vxz-Q1I3dVFdEypkRovE12EZBUaUc8fkUOdP9IzuuDtyzT23MXFjfZJOEjJOGn7_fMjP0Ozo5VlqN4hDo02glQ.jpg (Caused by ResponseError('too many 500 error responses'))"}
3
+ {"id": 7064, "description": "На фото запечатлена полка в магазине. На ней стоят четыре фигурки полосатых котят. \nПервый котёнок закрывает лапками глаза. Над ним текст: «Не вижу зла».\nВторой котёнок закрывает ушки. Над ним текст: «Не слышу зла».\nТретий котёнок закрывает лапками рот. Над ним текст: «Не говорю о зле».\nЧетвёртый котёнок стоит, положив лапки на живот. Над ним текст: «Хочу писять».\nНа картинке присутствует вотермарка @ villoyk8", "photo_urls": ["https://cdn4.telesco.pe/file/QC14QPqkqyPzP2uzCq93P_HoKBM4nePgT3ICF7JvpWUiqxfF1MhhKTN_UuK-5lCywybbbMDx9U2px_BTTOBT0yaMCCw-chz3jkfXzGtdB3TYQu0Kdk2GeghxujZFEiCf8X3YagqDTf1LAsjhMSSAepvFk5Ppo3VD4el2JoGfCVADLCvF3PIJXl8za5Id6ffSarg_Ifdv5FFkG1rXG6sucZlDrdvEaOU8Hs-L0F3CJCLvgMEif9N2-fFQ5dZ81dymCAtGV7DSiK_jqiP6WXl66H8_LLooMWZXAuhhsUtqxQVyY7qs9nzJ_9EN1YRrdizPcXbd3JfFWXhTFGDKwpLh0Q.jpg"], "source_url": "https://t.me/text_meme/7064", "published_at": "2025-08-21T06:18:52+00:00", "page_sha256": "ceca399ea6baa0936c36c60770686ade1f50e771a5127c3c9ea03b3bdbf70512", "fetched_at": "2026-10-15T11:23:23.502705+00:00", "reason": "RetryError: HTTPSConnectionPool(host='cdn4.telesco.pe', port=443): Max retries exceeded with url: /file/QC14QPqkqyPzP2uzCq93P_HoKBM4nePgT3ICF7JvpWUiqxfF1MhhKTN_UuK-5lCywybbbMDx9U2px_BTTOBT0yaMCCw-chz3jkfXzGtdB3TYQu0Kdk2GeghxujZFEiCf8X3YagqDTf1LAsjhMSSAepvFk5Ppo3VD4el2JoGfCVADLCvF3PIJXl8za5Id6ffSarg_Ifdv5FFkG1rXG6sucZlDrdvEaOU8Hs-L0F3CJCLvgMEif9N2-fFQ5dZ81dymCAtGV7DSiK_jqiP6WXl66H8_LLooMWZXAuhhsUtqxQVyY7qs9nzJ_9EN1YRrdizPcXbd3JfFWXhTFGDKwpLh0Q.jpg (Caused by ResponseError('too many 500 error responses'))"}
4
+ {"id": 7298, "description": "Кадр в плохом качестве, на котором запечатлён кенгуру по имени Dababy («Малыш»), живущий на территории Urban Rescue Ranch, приюта и реабилитационного центра для животных с одноимённым YouTube-каналом. \nТекст сверху и снизу: \n«\"you're acting crazy\" \nfirst of all i'm not acting \n(\"ведёшь себя как сумасшедший\" \nначнём с того, что не \"как\")».", "photo_urls": ["https://cdn4.telesco.pe/file/aebya8hVzvrzyK15Kc6Y99y475OswLXEVsqPs4Qz7MCXZ8HHdAKkEj5EjgIK0coC9qIqm_NleL9VPXch-_86aHCvP8wn3gT-C7xBNPE3uynugm3r5GrLVtbDgf_LpwDsktXQAEuimKUcSh1b3k5viswdJYrj7uAxjOGgWTxXshTQLHZ-pR6918KDKJbFbTA6V9bxcznQap1ZxLKuGztdsBlO_dLBblxMY3IoidDIdDaOXbLz0Ci7ayuUs3EdoSiPht27rtk3ZgY7NUxY9Bz3wV6gfpaFWwRaIy6MGKs0e7KRSTI-PaDdVkeJc-3ChL_OqOIw_e7Mqg6LtMDgmNlIKQ.jpg"], "source_url": "https://t.me/text_meme/7298", "published_at": "2025-10-24T10:25:45+00:00", "page_sha256": "a0ef89a43ad3f39e88afe5ccb93e1044e7fce71f5839d8488b838e29b337b8b9", "fetched_at": "2026-10-15T11:23:14.971012+00:00", "reason": "RetryError: HTTPSConnectionPool(host='cdn4.telesco.pe', port=443): Max retries exceeded with url: /file/aebya8hVzvrzyK15Kc6Y99y475OswLXEVsqPs4Qz7MCXZ8HHdAKkEj5EjgIK0coC9qIqm_NleL9VPXch-_86aHCvP8wn3gT-C7xBNPE3uynugm3r5GrLVtbDgf_LpwDsktXQAEuimKUcSh1b3k5viswdJYrj7uAxjOGgWTxXshTQLHZ-pR6918KDKJbFbTA6V9bxcznQap1ZxLKuGztdsBlO_dLBblxMY3IoidDIdDaOXbLz0Ci7ayuUs3EdoSiPht27rtk3ZgY7NUxY9Bz3wV6gfpaFWwRaIy6MGKs0e7KRSTI-PaDdVkeJc-3ChL_OqOIw_e7Mqg6LtMDgmNlIKQ.jpg (Caused by ResponseError('too many 500 error responses'))"}
provenance.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
scraper/.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .venv/
2
+ .cache/
3
+ work/
4
+ __pycache__/
5
+ .pytest_cache/
6
+ *.egg-info/
scraper/README.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # text_meme: обновление датасета
2
+
3
+ Возобновляемый скрапер публичного канала [«текстовые мемы»](https://t.me/text_meme)
4
+ для [d0rj/text_meme](https://huggingface.co/datasets/d0rj/text_meme).
5
+ Telegram-аккаунт, API ID и номер телефона не требуются.
6
+
7
+ ## Установка
8
+
9
+ Python 3.11+; команды из корня проекта:
10
+
11
+ ```powershell
12
+ python -m venv .venv
13
+ .venv\Scripts\python.exe -m pip install -r requirements.txt
14
+ ```
15
+
16
+ При использовании uv задайте локальный кеш, если системный кеш недоступен:
17
+
18
+ ```powershell
19
+ $env:UV_CACHE_DIR = "$PWD\.cache\uv"
20
+ uv venv .venv
21
+ uv pip install --python .venv\Scripts\python.exe -r requirements.txt
22
+ ```
23
+
24
+ ## Обновление
25
+
26
+ ```powershell
27
+ .venv\Scripts\python.exe text_meme.py snapshot
28
+ .venv\Scripts\python.exe text_meme.py crawl
29
+ .venv\Scripts\python.exe text_meme.py media
30
+ .venv\Scripts\python.exe text_meme.py export
31
+ .venv\Scripts\python.exe -m pytest -q
32
+ .venv\Scripts\python.exe scripts\verify_release.py
33
+ ```
34
+
35
+ `snapshot` фиксирует ревизию HF и SHA-256 всех исходных Parquet-файлов.
36
+ `crawl` идёт от свежей страницы назад до максимального ID из исходного датасета.
37
+ Верхняя граница фиксируется на первой странице; появившиеся позднее посты попадут
38
+ в следующий запуск. Для ограничения пилота используйте `crawl --max-pages 2`.
39
+ Для продолжения повторите `crawl`; состояние сохраняется после каждой страницы.
40
+
41
+ `media` скачивает JPEG из публичной веб-ленты в 6 потоков, проверяет декодирование
42
+ каждого изображения, сохраняет хеши и повторяет незавершённые загрузки. Все
43
+ сетевые запросы имеют таймауты и повторные попытки, в том числе для 429.
44
+ Страницы запрашиваются последовательно с паузой 0,5 с.
45
+
46
+ `export` требует завершённого обхода и отсутствия ошибок медиа. Результат:
47
+
48
+ - `work/release/data/train-update-*.parquet` — новые строки; схема `id`,
49
+ `description`, `photos: large_list<image>` и HF metadata взяты из исходного файла.
50
+ - `work/release/README.md` — обновлённые размеры и описание процедуры.
51
+ - `work/release/provenance.jsonl` — URL постов, время публикации/загрузки,
52
+ хеши HTML и каждого изображения.
53
+ - `work/release/audit.json` — числа, исключения, границы обхода и хеши файлов.
54
+ - `work/release/deferred.jsonl` — посты с недоступными медиа, если они явно отложены.
55
+
56
+ Если отдельные картинки стабильно недоступны на стороне Telegram, сначала
57
+ повторите `media`. Для выпуска доступной части используйте `media --defer-errors`:
58
+ после повторных попыток такие посты получат статус `deferred`, останутся в
59
+ инвентаре для восстановления и не попадут в train. Повторный `media` пробует
60
+ скачать также отложенные посты. Обычный `media` никогда не пропускает ошибки молча.
61
+
62
+ Оригинальные файлы не переписываются. Дедупликация идёт по ID Telegram-поста.
63
+ Одинаковые картинки в разных постах сохраняются: описания могут различаться.
64
+ Пост без описания или без фото исключается с записанной причиной.
65
+ Форматирование HTML удаляется, переносы строк описаний сохраняются.
66
+ `scripts/verify_release.py` независимо проверяет хеши старых файлов, схему и HF
67
+ metadata, уникальность всех ID, соответствие provenance и полное декодирование
68
+ изображений из старой версии и добавления.
69
+
70
+ ## Публикация
71
+
72
+ Сначала проверьте `work/release/audit.json`. Авторизация берётся из стандартного
73
+ хранилища Hugging Face или `HF_TOKEN`; секреты в проект не записываются.
74
+
75
+ ```powershell
76
+ hf auth whoami
77
+ .venv\Scripts\python.exe text_meme.py publish
78
+ ```
79
+
80
+ П��бликация выполняется одним коммитом с проверкой исходной ревизии, чтобы
81
+ не затереть параллельные изменения. `work/published.json` сохраняет SHA коммита.
82
+ Для следующего обновления используйте новый каталог состояния, например:
83
+
84
+ ```powershell
85
+ .venv\Scripts\python.exe text_meme.py --work work/next snapshot
86
+ .venv\Scripts\python.exe text_meme.py --work work/next crawl
87
+ .venv\Scripts\python.exe text_meme.py --work work/next media
88
+ .venv\Scripts\python.exe text_meme.py --work work/next export
89
+ .venv\Scripts\python.exe text_meme.py --work work/next publish
90
+ ```
91
+
92
+ ## Границы данных
93
+
94
+ Публичная HTML-лента отдаёт веб-превью фото. Полное разрешение исходных файлов
95
+ Telegram API не заявляется. Удалённые/недоступные посты и пропуски ниже старого
96
+ максимального ID не восстанавливаются. Пропуски ID в отчёте — это отсутствие в
97
+ наблюдаемой ленте; причина удаления не предполагается.
98
+
99
+ Исходная лицензионная метка датасета сохраняется. Она сама по себе не доказывает
100
+ права на сторонние изображения и произведения, изображённые в мемах.
101
+
102
+ Локально сохраняются `work/raw/*.html.gz`, SQLite WAL и скачанные картинки;
103
+ они не входят в Git. Публичный релиз содержит встроенные изображения,
104
+ проверяемый аудит и происхождение добавленных примеров.
scraper/pyproject.toml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [tool.pytest.ini_options]
2
+ pythonpath = ["."]
3
+ testpaths = ["tests"]
4
+ addopts = "--basetemp=work/pytest-temp"
scraper/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Versions used for the validated 2026-10-15 update. Python 3.11+.
2
+ beautifulsoup4==4.15.0
3
+ huggingface-hub==0.35.3
4
+ Pillow==12.0.0
5
+ pyarrow==25.0.0
6
+ requests==2.32.5
7
+ PyYAML==6.0.3
8
+ pytest==9.1.1
9
+ datasets==5.0.0
scraper/scripts/verify_release.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independently check a prepared release against its preserved baseline."""
2
+ import argparse
3
+ import hashlib
4
+ import io
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from PIL import Image
9
+ import pyarrow.parquet as pq
10
+
11
+
12
+ def digest(path):
13
+ with Path(path).open("rb") as file:
14
+ return hashlib.file_digest(file, "sha256").hexdigest()
15
+
16
+
17
+ def verify(work):
18
+ release = work / "release"
19
+ audit = json.loads((release / "audit.json").read_text(encoding="utf-8"))
20
+ provenance = [json.loads(line) for line in (release / "provenance.jsonl").read_text(encoding="utf-8").splitlines()]
21
+ source = {p["id"]: p for p in provenance}
22
+ assert len(source) == len(provenance) == audit["added_rows"]
23
+ paths = []
24
+ for item in audit["baseline_files"]:
25
+ path = work / "baseline" / item["path"]
26
+ assert digest(path) == item["sha256"], f"Baseline changed: {path}"
27
+ paths.append(path)
28
+ update = release / audit["new_parquet"]["path"]
29
+ assert digest(update) == audit["new_parquet"]["sha256"]
30
+ paths.append(update)
31
+ schema = pq.read_schema(paths[0])
32
+ ids = set()
33
+ rows = images = new_images = 0
34
+ legacy_null_descriptions = []
35
+ for path in paths:
36
+ assert pq.read_schema(path).equals(schema, check_metadata=True), f"Schema changed: {path}"
37
+ for batch in pq.ParquetFile(path).iter_batches(batch_size=64):
38
+ for row in batch.to_pylist():
39
+ assert row["id"] not in ids, f"Duplicate ID: {row['id']}"
40
+ ids.add(row["id"])
41
+ assert row["photos"]
42
+ if path == update:
43
+ assert row["description"] and row["description"].strip()
44
+ post = source[row["id"]]
45
+ assert row["description"] == post["description"]
46
+ assert len(row["photos"]) == len(post["photos"])
47
+ assert audit["crawl"]["since_id"] < row["id"] <= audit["crawl"]["upper_id"]
48
+ elif not row["description"]:
49
+ legacy_null_descriptions.append(row["id"])
50
+ for index, photo in enumerate(row["photos"]):
51
+ data = photo["bytes"]
52
+ assert data
53
+ with Image.open(io.BytesIO(data)) as image:
54
+ image.load()
55
+ if path == update:
56
+ entry = post["photos"][index]
57
+ assert list(image.size) == [entry["width"], entry["height"]]
58
+ assert hashlib.sha256(data).hexdigest() == entry["sha256"]
59
+ new_images += 1
60
+ images += 1
61
+ rows += 1
62
+ assert rows == audit["total_rows"]
63
+ assert new_images == audit["new_images"]
64
+ result = {"total_rows": rows, "total_images_decoded": images, "new_rows": len(provenance),
65
+ "new_images_decoded": new_images, "unique_ids": len(ids), "old_files_unchanged": True,
66
+ "preserved_legacy_missing_description_ids": legacy_null_descriptions,
67
+ "schema_and_hf_metadata_preserved": True}
68
+ (work / "verification.json").write_text(json.dumps(result, indent=2)+"\n", encoding="utf-8")
69
+ print(json.dumps(result))
70
+
71
+
72
+ if __name__ == "__main__":
73
+ parser = argparse.ArgumentParser(description=__doc__)
74
+ parser.add_argument("--work", type=Path, default=Path("work"))
75
+ verify(parser.parse_args().work)
scraper/tests/test_scraper.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import pyarrow as pa
6
+ import pyarrow.parquet as pq
7
+ from PIL import Image
8
+ import pytest
9
+
10
+ import text_meme as tm
11
+
12
+
13
+ def page(ids, cursor=None, photos=1, text="Русский <b>текст</b><br/>строка &amp; ещё"):
14
+ blocks = []
15
+ for post_id in ids:
16
+ media = "".join(
17
+ f'''<a class="tgme_widget_message_photo_wrap" style="background-image:url('https://cdn4.telesco.pe/{post_id}-{i}.jpg')"></a>'''
18
+ for i in range(photos)
19
+ )
20
+ blocks.append(f'''<div class="tgme_widget_message" data-post="text_meme/{post_id}">
21
+ {media}<div class="tgme_widget_message_text">{text}</div>
22
+ <time datetime="2026-10-15T08:00:00+00:00"></time></div>''')
23
+ more = f'<a class="js-messages_more" data-before="{cursor}"></a>' if cursor is not None else ""
24
+ return (more + "".join(blocks)).encode("utf-8")
25
+
26
+
27
+ def make_work(tmp_path):
28
+ root = tmp_path / "baseline" / "data"
29
+ root.mkdir(parents=True)
30
+ pic = io.BytesIO()
31
+ Image.new("RGB", (12, 8), "white").save(pic, format="JPEG")
32
+ data = pic.getvalue()
33
+ schema = pa.schema([
34
+ ("id", pa.int64()), ("description", pa.string()),
35
+ ("photos", pa.large_list(pa.struct([("bytes", pa.binary()), ("path", pa.string())]))),
36
+ ], metadata={b"huggingface": b'{"info":{"features":{"id":{"dtype":"int64","_type":"Value"},"description":{"dtype":"string","_type":"Value"},"photos":{"feature":{"_type":"Image"},"_type":"LargeList"}}}}'})
37
+ table = pa.Table.from_pylist([{"id": 10, "description": "original", "photos": [{"bytes": data, "path": None}]}], schema=schema)
38
+ file = root / "train-00000-of-00001.parquet"
39
+ pq.write_table(table, file)
40
+ card = """---
41
+ dataset_info:
42
+ features:
43
+ - name: id
44
+ dtype: int64
45
+ - name: description
46
+ dtype: string
47
+ - name: photos
48
+ large_list: image
49
+ splits:
50
+ - name: train
51
+ num_examples: 1
52
+ num_bytes: 1000
53
+ download_size: 900
54
+ dataset_size: 1000
55
+ configs:
56
+ - config_name: default
57
+ data_files:
58
+ - split: train
59
+ path: data/train-*
60
+ license: apache-2.0
61
+ ---
62
+
63
+ # Original card
64
+ """
65
+ (tmp_path / "baseline" / "README.md").write_text(card, encoding="utf-8")
66
+ baseline = {"revision": "old", "rows": 1, "min_id": 10, "max_id": 10,
67
+ "files": [{"path": "data/"+file.name, "sha256": tm.file_hash(file), "bytes": file.stat().st_size}]}
68
+ tm.atomic_json(tmp_path / "baseline.json", baseline)
69
+ return data, pq.read_table(file)
70
+
71
+
72
+ class Response:
73
+ def __init__(self, data):
74
+ self.content = data
75
+
76
+ def raise_for_status(self):
77
+ pass
78
+
79
+
80
+ class FakeSession:
81
+ def __init__(self, responses):
82
+ self.responses = iter(responses)
83
+
84
+ def get(self, url, **kwargs):
85
+ return Response(next(self.responses))
86
+
87
+
88
+ def test_utf8_html_linebreaks_inline_formatting_and_album():
89
+ posts, cursor = tm.parse_page(page([22], 22, photos=2))
90
+ assert cursor == 22
91
+ assert posts[0]["description"] == "Русский текст\nстрока & ещё"
92
+ assert len(posts[0]["photo_urls"]) == 2
93
+ assert posts[0]["source_url"] == "https://t.me/text_meme/22"
94
+
95
+
96
+ @pytest.mark.parametrize("data", [b"<html>challenge</html>", page([20]).replace(b"text_meme/", b"wrong/"), page([20]).replace(b"background-image", b"no-image")])
97
+ def test_reject_changed_or_unexpected_html(data):
98
+ with pytest.raises(ValueError):
99
+ tm.parse_page(data)
100
+
101
+
102
+ def test_crawl_resume_deduplicates_pages_and_reaches_boundary(tmp_path, monkeypatch):
103
+ make_work(tmp_path)
104
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([14, 15], 14)]))
105
+ tm.crawl(tmp_path, delay=0, max_pages=1)
106
+ assert not json.loads((tmp_path / "crawl-state.json").read_text())["complete"]
107
+ # Repeated ID on adjacent pages remains one record.
108
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([10, 11, 12, 14], 10)]))
109
+ tm.crawl(tmp_path, delay=0)
110
+ db = tm.db_open(tmp_path)
111
+ assert [i for i, in db.execute("SELECT id FROM posts ORDER BY id")] == [11, 12, 14, 15]
112
+ assert json.loads((tmp_path / "crawl-state.json").read_text())["complete"]
113
+ db.close()
114
+
115
+
116
+ def test_stalled_pagination_cannot_be_published(tmp_path, monkeypatch):
117
+ make_work(tmp_path)
118
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([14, 15], 14), page([14, 15], 14)]))
119
+ with pytest.raises(RuntimeError, match="advancing"):
120
+ tm.crawl(tmp_path, delay=0)
121
+ with pytest.raises(ValueError, match="boundary"):
122
+ tm.export(tmp_path)
123
+
124
+
125
+ def test_crawl_excludes_text_only_and_empty_descriptions(tmp_path, monkeypatch):
126
+ make_work(tmp_path)
127
+ content = page([10, 11], 10, photos=0) + page([12], text="")
128
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([content]))
129
+ tm.crawl(tmp_path, delay=0)
130
+ db = tm.db_open(tmp_path)
131
+ assert db.execute("SELECT id,reason FROM posts ORDER BY id").fetchall() == [(11, "no_photos"), (12, "no_description")]
132
+ db.close()
133
+
134
+
135
+ def test_end_to_end_export_preserves_old_shard_schema_and_images(tmp_path, monkeypatch):
136
+ data, original = make_work(tmp_path)
137
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([10, 11], 10)]))
138
+ tm.crawl(tmp_path, delay=0)
139
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([data]))
140
+ tm.media(tmp_path, workers=1)
141
+ tm.export(tmp_path)
142
+ audit = json.loads((tmp_path / "release" / "audit.json").read_text())
143
+ assert audit["added_rows"] == 1
144
+ assert audit["total_rows"] == 2
145
+ assert audit["unobserved_message_ids"] == []
146
+ old = pq.read_table(tmp_path / "baseline" / "data" / "train-00000-of-00001.parquet")
147
+ new = pq.read_table(tmp_path / "release" / audit["new_parquet"]["path"])
148
+ assert old.equals(original, check_metadata=True)
149
+ assert old.schema == new.schema
150
+ assert new["photos"][0].as_py()[0]["bytes"] == data
151
+ assert new["description"][0].as_py() == "Русский текст\nстрока & ещё"
152
+ assert "# Original card" in (tmp_path / "release" / "README.md").read_text(encoding="utf-8")
153
+
154
+
155
+ def test_failed_media_blocks_export_and_can_resume(tmp_path, monkeypatch):
156
+ data, _ = make_work(tmp_path)
157
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([10, 11], 10)]))
158
+ tm.crawl(tmp_path, delay=0)
159
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([b"<html>no image</html>"]))
160
+ with pytest.raises(RuntimeError, match="media errors"):
161
+ tm.media(tmp_path, workers=1)
162
+ with pytest.raises(ValueError, match="Unresolved"):
163
+ tm.export(tmp_path)
164
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([data]))
165
+ tm.media(tmp_path, workers=1)
166
+ tm.export(tmp_path)
167
+
168
+
169
+ def test_publish_rejects_concurrent_remote_change(tmp_path, monkeypatch):
170
+ tm.atomic_json(tmp_path / "release" / "audit.json", {"baseline_revision": "old"})
171
+
172
+ class Api:
173
+ def dataset_info(self, repo):
174
+ return type("Info", (), {"sha": "new"})()
175
+
176
+ def create_commit(self, *args, **kwargs):
177
+ pytest.fail("Must not publish over concurrent changes")
178
+
179
+ monkeypatch.setattr(tm, "HfApi", Api)
180
+ with pytest.raises(ValueError, match="Remote changed"):
181
+ tm.publish(tmp_path)
182
+
183
+
184
+ def test_unavailable_media_explicitly_deferred_with_recovery_inventory(tmp_path, monkeypatch):
185
+ data, _ = make_work(tmp_path)
186
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([10, 11, 12], 10)]))
187
+ tm.crawl(tmp_path, delay=0)
188
+
189
+ def fetch(work, post):
190
+ if post["id"] == 12:
191
+ raise RuntimeError("source media unavailable")
192
+ return original_fetch(work, post)
193
+
194
+ original_fetch = tm.fetch_photos
195
+ monkeypatch.setattr(tm, "fetch_photos", fetch)
196
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([data]))
197
+ tm.media(tmp_path, workers=1, defer_errors=True)
198
+ tm.export(tmp_path)
199
+ audit = json.loads((tmp_path / "release" / "audit.json").read_text())
200
+ assert audit["added_rows"] == 1
201
+ assert audit["deferred_media_ids"] == [12]
202
+ deferred = json.loads((tmp_path / "release" / "deferred.jsonl").read_text(encoding="utf-8"))
203
+ assert deferred["id"] == 12
204
+ assert deferred["source_url"].endswith("/12")
205
+ assert deferred["reason"] == "RuntimeError: source media unavailable"
206
+ monkeypatch.setattr(tm, "fetch_photos", original_fetch)
207
+ tm.media(tmp_path, workers=1)
208
+ tm.export(tmp_path)
209
+ audit = json.loads((tmp_path / "release" / "audit.json").read_text())
210
+ assert audit["added_rows"] == 2
211
+ assert audit["deferred_media_ids"] == []
212
+
213
+
214
+ def test_verifier_records_legacy_null_label_without_modifying_baseline(tmp_path, monkeypatch):
215
+ from scripts.verify_release import verify
216
+
217
+ data, old = make_work(tmp_path)
218
+ rows = old.to_pylist()
219
+ rows[0]["description"] = None
220
+ original = tmp_path / "baseline" / "data" / "train-00000-of-00001.parquet"
221
+ pq.write_table(pa.Table.from_pylist(rows, schema=old.schema), original)
222
+ baseline = json.loads((tmp_path / "baseline.json").read_text())
223
+ baseline["files"][0]["sha256"] = tm.file_hash(original)
224
+ tm.atomic_json(tmp_path / "baseline.json", baseline)
225
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([page([10, 11], 10)]))
226
+ tm.crawl(tmp_path, delay=0)
227
+ monkeypatch.setattr(tm, "session", lambda: FakeSession([data]))
228
+ tm.media(tmp_path, workers=1)
229
+ tm.export(tmp_path)
230
+ verify(tmp_path)
231
+ verified = json.loads((tmp_path / "verification.json").read_text())
232
+ assert verified["preserved_legacy_missing_description_ids"] == [10]
233
+ assert verified["total_rows"] == 2
234
+ assert tm.file_hash(original) == baseline["files"][0]["sha256"]
scraper/text_meme.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Update d0rj/text_meme from Telegram's public HTML archive, without login."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from datetime import datetime, timezone
7
+ import gzip
8
+ import hashlib
9
+ import io
10
+ import json
11
+ from pathlib import Path
12
+ import re
13
+ import sqlite3
14
+ import time
15
+ import shutil
16
+
17
+ from bs4 import BeautifulSoup
18
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
19
+ from PIL import Image
20
+ import pyarrow as pa
21
+ import pyarrow.parquet as pq
22
+ import requests
23
+ from requests.adapters import HTTPAdapter
24
+ from urllib3.util.retry import Retry
25
+ import yaml
26
+
27
+ REPO = "d0rj/text_meme"
28
+ CHANNEL = "text_meme"
29
+ BASE_URL = f"https://t.me/s/{CHANNEL}"
30
+
31
+
32
+ def now():
33
+ return datetime.now(timezone.utc).isoformat()
34
+
35
+
36
+ def sha256(data):
37
+ return hashlib.sha256(data).hexdigest()
38
+
39
+
40
+ def file_hash(path):
41
+ h = hashlib.sha256()
42
+ with Path(path).open("rb") as f:
43
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
44
+ h.update(chunk)
45
+ return h.hexdigest()
46
+
47
+
48
+ def atomic_json(path, value):
49
+ path = Path(path)
50
+ path.parent.mkdir(parents=True, exist_ok=True)
51
+ temp = path.with_suffix(path.suffix + ".tmp")
52
+ temp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
53
+ temp.replace(path)
54
+
55
+
56
+ def session():
57
+ s = requests.Session()
58
+ s.headers["User-Agent"] = "text-meme-dataset-updater/0.1 (+https://huggingface.co/datasets/d0rj/text_meme)"
59
+ retry = Retry(total=5, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], respect_retry_after_header=True)
60
+ s.mount("https://", HTTPAdapter(max_retries=retry))
61
+ return s
62
+
63
+
64
+ def db_open(work):
65
+ work.mkdir(parents=True, exist_ok=True)
66
+ db = sqlite3.connect(work / "crawl.sqlite")
67
+ db.execute("PRAGMA journal_mode=WAL")
68
+ db.execute("CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY, post TEXT NOT NULL, status TEXT NOT NULL, reason TEXT)")
69
+ db.execute("CREATE TABLE IF NOT EXISTS pages (sha256 TEXT PRIMARY KEY, url TEXT NOT NULL, fetched_at TEXT NOT NULL, path TEXT NOT NULL)")
70
+ return db
71
+
72
+
73
+ def parse_page(content):
74
+ # Telegram omits charset in some responses. Never let a detector guess Cyrillic.
75
+ soup = BeautifulSoup(content.decode("utf-8"), "html.parser")
76
+ posts = []
77
+ for node in soup.select(".tgme_widget_message[data-post]"):
78
+ channel, post_id = node["data-post"].rsplit("/", 1)
79
+ if channel != CHANNEL or not post_id.isdigit():
80
+ raise ValueError("Unexpected Telegram channel/message identifier")
81
+ text = node.select_one(".tgme_widget_message_text")
82
+ if text:
83
+ for br in text.select("br"):
84
+ br.replace_with("\n")
85
+ description = text.get_text().replace("\r\n", "\n").strip()
86
+ else:
87
+ description = ""
88
+ photos = []
89
+ for photo in node.select(".tgme_widget_message_photo_wrap"):
90
+ match = re.search(r"background-image\s*:\s*url\(['\"]?(.*?)['\"]?\)", photo.get("style", ""))
91
+ if not match:
92
+ raise ValueError(f"Photo URL missing for post {post_id}")
93
+ url = match.group(1)
94
+ if url not in photos:
95
+ photos.append(url)
96
+ stamp = node.select_one("time[datetime]")
97
+ posts.append({"id": int(post_id), "description": description, "photo_urls": photos,
98
+ "source_url": f"https://t.me/{CHANNEL}/{post_id}",
99
+ "published_at": stamp["datetime"] if stamp else None})
100
+ more = soup.select_one(".js-messages_more[data-before]")
101
+ cursor = int(more["data-before"]) if more else None
102
+ if not posts and not soup.select_one(".tme_no_messages"):
103
+ raise ValueError("No Telegram messages found; possible block or changed HTML")
104
+ return posts, cursor
105
+
106
+
107
+ def snapshot(work):
108
+ api = HfApi()
109
+ info = api.dataset_info(REPO, files_metadata=True)
110
+ root = work / "baseline"
111
+ root.mkdir(parents=True, exist_ok=True)
112
+ card = hf_hub_download(REPO, "README.md", repo_type="dataset", revision=info.sha, local_dir=root)
113
+ files = []
114
+ ids = []
115
+ rows = 0
116
+ for item in info.siblings:
117
+ if item.rfilename.startswith("data/train-") and item.rfilename.endswith(".parquet"):
118
+ path = Path(hf_hub_download(REPO, item.rfilename, repo_type="dataset", revision=info.sha, local_dir=root))
119
+ table = pq.read_table(path, columns=["id"])
120
+ ids.extend(table["id"].to_pylist())
121
+ rows += len(table)
122
+ files.append({"path": item.rfilename, "sha256": file_hash(path), "bytes": path.stat().st_size})
123
+ if not files or not ids or len(ids) != len(set(ids)):
124
+ raise ValueError("Baseline missing or contains duplicate IDs")
125
+ manifest = {"repo": REPO, "revision": info.sha, "downloaded_at": now(), "rows": rows,
126
+ "min_id": min(ids), "max_id": max(ids), "files": files,
127
+ "card_sha256": file_hash(card)}
128
+ atomic_json(work / "baseline.json", manifest)
129
+ print(json.dumps(manifest), flush=True)
130
+
131
+
132
+ def crawl(work, since_id=None, delay=0.5, max_pages=None):
133
+ baseline = json.loads((work / "baseline.json").read_text(encoding="utf-8"))
134
+ since_id = baseline["max_id"] if since_id is None else since_id
135
+ db = db_open(work)
136
+ state_path = work / "crawl-state.json"
137
+ state = json.loads(state_path.read_text(encoding="utf-8")) if state_path.exists() else {}
138
+ if state.get("complete") or not state:
139
+ state = {"started_at": now(), "since_id": since_id, "upper_id": None, "cursor": None, "complete": False, "pages": 0}
140
+ if state["since_id"] != since_id:
141
+ raise ValueError("Resume cutoff differs. Use a separate --work directory for another cutoff.")
142
+ client = session()
143
+ page_count = 0
144
+ while True:
145
+ cursor = state["cursor"]
146
+ url = BASE_URL + (f"?before={cursor}" if cursor is not None else "")
147
+ response = client.get(url, timeout=(15, 60))
148
+ response.raise_for_status()
149
+ posts, next_cursor = parse_page(response.content)
150
+ if not posts:
151
+ raise RuntimeError("Archive ended before the baseline boundary; refusing to claim coverage")
152
+ if state["upper_id"] is None:
153
+ state["upper_id"] = max(p["id"] for p in posts)
154
+ digest = sha256(response.content)
155
+ raw = work / "raw" / (digest + ".html.gz")
156
+ raw.parent.mkdir(exist_ok=True)
157
+ if not raw.exists():
158
+ raw.write_bytes(gzip.compress(response.content, mtime=0))
159
+ fetched = now()
160
+ with db:
161
+ db.execute("INSERT OR IGNORE INTO pages VALUES (?,?,?,?)", (digest, url, fetched, raw.relative_to(work).as_posix()))
162
+ for post in posts:
163
+ if not since_id < post["id"] <= state["upper_id"]:
164
+ continue
165
+ post.update(page_sha256=digest, fetched_at=fetched)
166
+ reason = "no_description" if not post["description"] else "no_photos" if not post["photo_urls"] else None
167
+ db.execute("INSERT OR IGNORE INTO posts VALUES (?,?,?,?)", (post["id"], json.dumps(post, ensure_ascii=False), "excluded" if reason else "pending", reason))
168
+ state["pages"] += 1
169
+ page_count += 1
170
+ reached = min(p["id"] for p in posts) <= since_id
171
+ if not reached and (next_cursor is None or (cursor is not None and next_cursor >= cursor)):
172
+ raise RuntimeError("Pagination stopped advancing before reaching the baseline")
173
+ state.update(cursor=next_cursor, complete=reached, updated_at=now())
174
+ atomic_json(state_path, state)
175
+ if page_count % 10 == 0 or reached:
176
+ print(json.dumps({"pages": state["pages"], "oldest_id": min(p["id"] for p in posts), "upper_id": state["upper_id"], "complete": reached}), flush=True)
177
+ if reached or (max_pages is not None and page_count >= max_pages):
178
+ break
179
+ time.sleep(delay)
180
+ db.close()
181
+
182
+
183
+ def read_image(data):
184
+ with Image.open(io.BytesIO(data)) as image:
185
+ width, height = image.size
186
+ image.verify()
187
+ with Image.open(io.BytesIO(data)) as image:
188
+ image.load()
189
+ return width, height
190
+
191
+
192
+ def fetch_photos(work, post):
193
+ client = session()
194
+ photos = []
195
+ for index, url in enumerate(post["photo_urls"]):
196
+ path = work / "media" / str(post["id"]) / f"{index:02d}.jpg"
197
+ path.parent.mkdir(parents=True, exist_ok=True)
198
+ if path.exists():
199
+ data = path.read_bytes()
200
+ else:
201
+ response = client.get(url, timeout=(15, 60))
202
+ response.raise_for_status()
203
+ data = response.content
204
+ read_image(data)
205
+ temp = path.with_suffix(".tmp")
206
+ temp.write_bytes(data)
207
+ temp.replace(path)
208
+ width, height = read_image(data)
209
+ photos.append({"path": path.relative_to(work).as_posix(), "sha256": sha256(data), "bytes": len(data), "width": width, "height": height})
210
+ return {**post, "photos": photos}
211
+
212
+
213
+ def media(work, workers=6, defer_errors=False):
214
+ db = db_open(work)
215
+ pending = db.execute("SELECT id, post FROM posts WHERE status IN ('pending','error','deferred') ORDER BY id DESC").fetchall()
216
+ errors = 0
217
+ with ThreadPoolExecutor(max_workers=workers) as pool:
218
+ futures = {pool.submit(fetch_photos, work, json.loads(raw)): post_id for post_id, raw in pending}
219
+ for count, future in enumerate(as_completed(futures), 1):
220
+ post_id = futures[future]
221
+ try:
222
+ post = future.result()
223
+ with db:
224
+ db.execute("UPDATE posts SET post=?,status='ready',reason=NULL WHERE id=?", (json.dumps(post, ensure_ascii=False), post_id))
225
+ except Exception as exc:
226
+ errors += 1
227
+ with db:
228
+ db.execute("UPDATE posts SET status='error',reason=? WHERE id=?", (f"{type(exc).__name__}: {exc}", post_id))
229
+ print(json.dumps({"error_id": post_id, "error": str(exc)}), flush=True)
230
+ if count % 100 == 0 or count == len(pending):
231
+ print(json.dumps({"media_processed": count, "total": len(pending), "errors": errors}), flush=True)
232
+ if errors and defer_errors:
233
+ with db:
234
+ db.execute("UPDATE posts SET status='deferred' WHERE status='error'")
235
+ print(json.dumps({"deferred_unavailable_posts": errors}), flush=True)
236
+ db.close()
237
+ if errors and not defer_errors:
238
+ raise RuntimeError(f"{errors} posts have media errors; rerun media before export")
239
+
240
+
241
+ def baseline_tables(work, baseline):
242
+ for file in baseline["files"]:
243
+ path = work / "baseline" / file["path"]
244
+ if file_hash(path) != file["sha256"]:
245
+ raise ValueError(f"Baseline changed: {file['path']}")
246
+ yield pq.read_table(path)
247
+
248
+
249
+ def export(work):
250
+ baseline = json.loads((work / "baseline.json").read_text(encoding="utf-8"))
251
+ state = json.loads((work / "crawl-state.json").read_text(encoding="utf-8"))
252
+ if not state["complete"]:
253
+ raise ValueError("Crawl has not reached the baseline boundary")
254
+ db = db_open(work)
255
+ counts = dict(db.execute("SELECT status,COUNT(*) FROM posts GROUP BY status"))
256
+ if counts.get("pending", 0) or counts.get("error", 0):
257
+ raise ValueError(f"Unresolved media: {counts}")
258
+ originals = list(baseline_tables(work, baseline))
259
+ schema = originals[0].schema
260
+ if schema.names != ["id", "description", "photos"] or any(t.schema != schema for t in originals):
261
+ raise ValueError("Unexpected baseline schema")
262
+ existing = {i for t in originals for i in t["id"].to_pylist()}
263
+ posts = [json.loads(raw) for _, raw in db.execute("SELECT id,post FROM posts WHERE status='ready' AND id>? AND id<=? ORDER BY id", (state["since_id"], state["upper_id"]))]
264
+ if not posts:
265
+ raise ValueError("No new eligible posts")
266
+ if existing.intersection(p["id"] for p in posts):
267
+ raise ValueError("New IDs overlap baseline IDs")
268
+ out = work / "release"
269
+ (out / "data").mkdir(parents=True, exist_ok=True)
270
+ name = f"data/train-update-{state['since_id']+1:08d}-{state['upper_id']:08d}.parquet"
271
+ target = out / name
272
+ rows = []
273
+ provenance = []
274
+ for post in posts:
275
+ images = []
276
+ for photo in post["photos"]:
277
+ data = (work / photo["path"]).read_bytes()
278
+ if sha256(data) != photo["sha256"]:
279
+ raise ValueError(f"Media changed: {photo['path']}")
280
+ read_image(data)
281
+ images.append({"bytes": data, "path": f"{post['id']}_{len(images):02d}.jpg"})
282
+ rows.append({"id": post["id"], "description": post["description"], "photos": images})
283
+ provenance.append({k: v for k, v in post.items() if k != "photo_urls"})
284
+ table = pa.Table.from_pylist(rows, schema=schema)
285
+ temp = target.with_suffix(".tmp")
286
+ pq.write_table(table, temp, compression="zstd")
287
+ temp.replace(target)
288
+ written = pq.read_table(target)
289
+ if not written.equals(table, check_metadata=True):
290
+ raise ValueError("Parquet roundtrip mismatch")
291
+ image_hashes = {}
292
+ for post in posts:
293
+ for photo in post["photos"]:
294
+ image_hashes.setdefault(photo["sha256"], []).append(post["id"])
295
+ duplicates = [sorted(set(ids)) for ids in image_hashes.values() if len(set(ids)) > 1]
296
+ cross_baseline = []
297
+ legacy_missing = []
298
+ for original in originals:
299
+ for batch in original.to_batches(max_chunksize=64):
300
+ for row in batch.to_pylist():
301
+ if not row["description"]:
302
+ legacy_missing.append(row["id"])
303
+ for photo in row["photos"]:
304
+ digest = sha256(photo["bytes"])
305
+ if digest in image_hashes:
306
+ cross_baseline.append({"baseline_id": row["id"], "new_ids": image_hashes[digest], "sha256": digest})
307
+ excluded = [{"id": i, "reason": reason} for i, reason in db.execute("SELECT id,reason FROM posts WHERE status='excluded' AND id>? AND id<=? ORDER BY id", (state["since_id"], state["upper_id"]))]
308
+ deferred = [{**json.loads(raw), "reason": reason} for raw, reason in db.execute("SELECT post,reason FROM posts WHERE status='deferred' AND id>? AND id<=? ORDER BY id", (state["since_id"], state["upper_id"]))]
309
+ seen = [i for i, in db.execute("SELECT id FROM posts WHERE id>? AND id<=? ORDER BY id", (state["since_id"], state["upper_id"]))]
310
+ missing_ids = sorted(set(range(state["since_id"]+1, state["upper_id"]+1)) - set(seen))
311
+ audit = {"repo": REPO, "baseline_revision": baseline["revision"], "generated_at": now(),
312
+ "baseline_rows": baseline["rows"], "added_rows": len(rows), "total_rows": baseline["rows"] + len(rows),
313
+ "new_id_min": min(p["id"] for p in posts), "new_id_max": max(p["id"] for p in posts),
314
+ "published_at_min": min(p["published_at"] for p in posts), "published_at_max": max(p["published_at"] for p in posts),
315
+ "new_images": sum(len(p["photos"]) for p in posts), "schema_preserved": True,
316
+ "new_data_num_bytes": table.nbytes, "new_parquet": {"path": name, "sha256": file_hash(target), "bytes": target.stat().st_size},
317
+ "baseline_files": baseline["files"], "crawl": state, "status_counts": counts,
318
+ "excluded": excluded, "unobserved_message_ids": missing_ids,
319
+ "deferred_media_ids": [p["id"] for p in deferred],
320
+ "exact_image_duplicate_groups_within_update": duplicates,
321
+ "exact_image_matches_to_baseline": cross_baseline,
322
+ "preserved_legacy_missing_description_ids": legacy_missing,
323
+ "dedup_policy": "Unique Telegram post ID; identical images in distinct annotated posts retained.",
324
+ "coverage": "Public HTML posts above baseline max ID through frozen first-page upper ID. Deleted/unavailable IDs and older holes are not recovered.",
325
+ "image_source": "Telegram public web preview JPEGs; original-resolution Telegram API files are not claimed."}
326
+ atomic_json(out / "audit.json", audit)
327
+ with (out / "provenance.jsonl").open("w", encoding="utf-8", newline="\n") as f:
328
+ for p in provenance:
329
+ f.write(json.dumps(p, ensure_ascii=False) + "\n")
330
+ with (out / "deferred.jsonl").open("w", encoding="utf-8", newline="\n") as f:
331
+ for p in deferred:
332
+ f.write(json.dumps(p, ensure_ascii=False) + "\n")
333
+ original_card = (work / "baseline" / "README.md").read_text(encoding="utf-8")
334
+ _, metadata, body = original_card.split("---", 2)
335
+ card = yaml.safe_load(metadata)
336
+ info = card["dataset_info"]
337
+ split = next(s for s in info["splits"] if s["name"] == "train")
338
+ split["num_examples"] = audit["total_rows"]
339
+ split["num_bytes"] += table.nbytes
340
+ info["download_size"] += target.stat().st_size
341
+ info["dataset_size"] += table.nbytes
342
+ # Keep existing dataset description intact; append a new, source-specific update section.
343
+ body += (f"\n\n## Incremental update {audit['generated_at'][:10]}\n\n"
344
+ f"Added **{len(rows):,}** posts (**{audit['new_images']:,}** images) from "
345
+ f"[the public Telegram channel](https://t.me/{CHANNEL}); train now has **{audit['total_rows']:,}** rows. "
346
+ f"New post IDs: {audit['new_id_min']}–{audit['new_id_max']}; dates: {audit['published_at_min']} to {audit['published_at_max']}.\n\n"
347
+ "The existing Parquet files and examples are preserved. Schema remains `id`, `description`, `photos` "
348
+ "(a large list of embedded images). Descriptions are channel annotations, with HTML formatting removed and line breaks preserved. "
349
+ "New images are Telegram public web previews; their resolution may differ from original Telegram files. "
350
+ "Posts require both a nonempty description and at least one valid photo. Deduplication uses Telegram post IDs; "
351
+ "reposted images with distinct annotations are retained.\n\n"
352
+ f"Excluded {len(excluded)} posts without text/photos; deferred {len(deferred)} posts with unavailable media "
353
+ "([retry inventory](deferred.jsonl)). "
354
+ f"The crawl reached the previous maximum message ID {baseline['max_id']}. "
355
+ "Deleted/unavailable posts, older gaps, and future posts are outside this update. "
356
+ "See [audit](audit.json) for exclusions, counts, hashes and coverage, and [provenance](provenance.jsonl) for source URLs, "
357
+ "timestamps and image hashes. The scraper and its tests are in [scraper](scraper/README.md).\n\n"
358
+ "The repository's existing Apache-2.0 metadata is retained. This does not establish ownership or permissions "
359
+ "for third-party meme images and underlying works.\n")
360
+ (out / "README.md").write_text("---\n" + yaml.safe_dump(card, allow_unicode=True, sort_keys=False) + "---" + body, encoding="utf-8")
361
+ source_root = Path(__file__).resolve().parent
362
+ for relative in ["text_meme.py", "README.md", "requirements.txt", "pyproject.toml", "tests/test_scraper.py", "scripts/verify_release.py"]:
363
+ source = source_root / relative
364
+ destination = out / "scraper" / relative
365
+ if source.exists():
366
+ destination.parent.mkdir(parents=True, exist_ok=True)
367
+ shutil.copyfile(source, destination)
368
+ db.close()
369
+ print(json.dumps({k: audit[k] for k in ["added_rows", "total_rows", "new_images", "new_id_min", "new_id_max", "status_counts"]}), flush=True)
370
+
371
+
372
+ def publish(work):
373
+ root = work / "release"
374
+ audit = json.loads((root / "audit.json").read_text(encoding="utf-8"))
375
+ api = HfApi()
376
+ current = api.dataset_info(REPO)
377
+ if current.sha != audit["baseline_revision"]:
378
+ raise ValueError("Remote changed since snapshot; rebuild against a fresh baseline before publishing")
379
+ target = root / audit["new_parquet"]["path"]
380
+ if file_hash(target) != audit["new_parquet"]["sha256"]:
381
+ raise ValueError("Release shard changed after validation")
382
+ files = [p for p in root.rglob("*") if p.is_file()]
383
+ commit = api.create_commit(REPO, repo_type="dataset", parent_commit=current.sha,
384
+ operations=[CommitOperationAdd(path_in_repo=p.relative_to(root).as_posix(), path_or_fileobj=p) for p in sorted(files)],
385
+ commit_message=f"Add {audit['added_rows']} Telegram meme posts through {audit['new_id_max']}",
386
+ commit_description=f"Preserve {audit['baseline_rows']} existing rows and schema; include source provenance, audit and resumable scraper.")
387
+ atomic_json(work / "published.json", {"repo": REPO, "revision": commit.oid, "url": commit.commit_url, "published_at": now()})
388
+ print(commit.commit_url, flush=True)
389
+
390
+
391
+ def main():
392
+ parser = argparse.ArgumentParser(description=__doc__)
393
+ parser.add_argument("--work", type=Path, default=Path("work"))
394
+ sub = parser.add_subparsers(dest="command", required=True)
395
+ sub.add_parser("snapshot")
396
+ c = sub.add_parser("crawl")
397
+ c.add_argument("--since-id", type=int)
398
+ c.add_argument("--delay", type=float, default=0.5)
399
+ c.add_argument("--max-pages", type=int)
400
+ m = sub.add_parser("media")
401
+ m.add_argument("--workers", type=int, default=6)
402
+ m.add_argument("--defer-errors", action="store_true", help="Record unavailable media in deferred.jsonl and permit exporting remaining posts")
403
+ sub.add_parser("export")
404
+ sub.add_parser("publish")
405
+ args = parser.parse_args()
406
+ if args.command == "crawl":
407
+ crawl(args.work, args.since_id, args.delay, args.max_pages)
408
+ elif args.command == "media":
409
+ media(args.work, args.workers, args.defer_errors)
410
+ else:
411
+ globals()[args.command](args.work)
412
+
413
+
414
+ if __name__ == "__main__":
415
+ main()
validation.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "total_rows": 8584,
3
+ "total_images_decoded": 8592,
4
+ "new_rows": 2345,
5
+ "new_images_decoded": 2345,
6
+ "unique_ids": 8584,
7
+ "old_files_unchanged": true,
8
+ "preserved_legacy_missing_description_ids": [
9
+ 622
10
+ ],
11
+ "schema_and_hf_metadata_preserved": true,
12
+ "tests": {
13
+ "command": ".venv\\Scripts\\python.exe -m pytest -q",
14
+ "passed": 12
15
+ },
16
+ "datasets_load": {
17
+ "rows": 8584,
18
+ "features": {
19
+ "id": "int64",
20
+ "description": "string",
21
+ "photos": "LargeList(Image)"
22
+ }
23
+ },
24
+ "python": "3.13.13",
25
+ "software_versions": {
26
+ "beautifulsoup4": "4.15.0",
27
+ "huggingface-hub": "0.35.3",
28
+ "Pillow": "12.0.0",
29
+ "pyarrow": "25.0.0",
30
+ "requests": "2.32.5",
31
+ "PyYAML": "6.0.3",
32
+ "pytest": "9.1.1",
33
+ "datasets": "5.0.0"
34
+ },
35
+ "scraper_files_sha256": {
36
+ "scraper/pyproject.toml": "12a3924755756c600fd608ba4f02aef337c2a9fa33fc8381c025f1b940d91cbe",
37
+ "scraper/README.md": "e6aa7eb99b06b53d333362e78c9843e807c90d70ad07d8ff24e8c38df6a45bd7",
38
+ "scraper/requirements.txt": "fad4121dc1c223beded64e12d208b21cb78e313cb0f343ef73d878e5155e9fbe",
39
+ "scraper/text_meme.py": "2f6c035cf01ef325d49ec95255b563c7dacf9dd6fff1c72d4e150032ea252c7b",
40
+ "scraper/scripts/verify_release.py": "26ddafb6549c90f4500cd035a6a27965ecfb2439973e7b1c3bc45975689c60ab",
41
+ "scraper/tests/test_scraper.py": "caafb9b9b45d70bde64fc06c5e5d2742e4f6caaa81983874733ef9a64d8d1ada"
42
+ }
43
+ }