Raidanameen commited on
Commit
69ed2c6
·
verified ·
1 Parent(s): c5a7b9b

Upload MuMiN-Build - MuMiN misinformation dataset builder toolkit

Browse files
.flake8 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [flake8]
2
+ ignore = E203, E266, E501, W503, F403, F401, C901
3
+ max-line-length = 87
4
+ max-complexity = 18
5
+ select = B,C,E,F,W,T4,B9
.github/workflows/ci.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - main
10
+
11
+ jobs:
12
+
13
+ lint:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+ - uses: jpetrucciani/black-check@master
18
+
19
+ pytest:
20
+ strategy:
21
+ matrix:
22
+ os:
23
+ - macos-latest
24
+ - windows-latest
25
+ - ubuntu-latest
26
+ python-version:
27
+ - '3.8'
28
+ - '3.9'
29
+ - '3.10'
30
+ runs-on: ${{ matrix.os }}
31
+ steps:
32
+ - uses: actions/checkout@v2
33
+
34
+ - name: Set up Python
35
+ uses: actions/setup-python@v2
36
+ with:
37
+ python-version: ${{ matrix.python-version }}
38
+
39
+ - name: Install Poetry
40
+ uses: abatilo/actions-poetry@v2.0.0
41
+ with:
42
+ poetry-version: 1.1.10
43
+
44
+ - name: Set Poetry config
45
+ run: |
46
+ poetry config virtualenvs.create true
47
+ poetry config virtualenvs.in-project false
48
+ poetry config virtualenvs.path ~/.virtualenvs
49
+
50
+ - name: Cache Poetry virtualenv
51
+ uses: actions/cache@v1
52
+ id: cache
53
+ with:
54
+ path: ~/.virtualenvs
55
+ key: poetry-${{ matrix.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }}
56
+ restore-keys: |
57
+ poetry-${{ matrix.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }}
58
+
59
+ - name: Install Dependencies
60
+ run: poetry install
61
+ if: steps.cache.outputs.cache-hit != 'true'
62
+
63
+ - name: Test with pytest
64
+ run: poetry run pytest -n 1
65
+ env:
66
+ TWITTER_API_KEY: ${{ secrets.TWITTER_API_KEY }}
.github/workflows/docs.yaml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: website
2
+
3
+ # Build the documentation whenever there are new commits on main
4
+ on:
5
+ push:
6
+ branches:
7
+ - main
8
+ pull_request:
9
+ branches:
10
+ - main
11
+ types:
12
+ - ready_for_review
13
+ - review_requested
14
+
15
+ # Security: restrict permissions for CI jobs.
16
+ permissions:
17
+ contents: read
18
+
19
+ jobs:
20
+ # Build the documentation and upload the static HTML files as an artifact.
21
+ build:
22
+ runs-on: ubuntu-latest
23
+ steps:
24
+ - uses: actions/checkout@v2
25
+
26
+ - name: Set up Python
27
+ uses: actions/setup-python@v2
28
+ with:
29
+ python-version: ${{ matrix.python-version }}
30
+
31
+ - name: Install Poetry
32
+ uses: abatilo/actions-poetry@v2.0.0
33
+ with:
34
+ poetry-version: 1.1.10
35
+
36
+ - name: Set Poetry config
37
+ run: |
38
+ poetry config virtualenvs.create true
39
+ poetry config virtualenvs.in-project false
40
+ poetry config virtualenvs.path ~/.virtualenvs
41
+
42
+ - name: Cache Poetry virtualenv
43
+ uses: actions/cache@v1
44
+ id: cache
45
+ with:
46
+ path: ~/.virtualenvs
47
+ key: poetry-${{ matrix.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }}
48
+ restore-keys: |
49
+ poetry-${{ matrix.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }}
50
+
51
+ - name: Install Dependencies
52
+ run: poetry install
53
+ if: steps.cache.outputs.cache-hit != 'true'
54
+
55
+ - name: Build documentation
56
+ run: poetry run pdoc --docformat google src/mumin -o docs
57
+
58
+ - name: Compress documentation
59
+ run: tar --directory docs/ -hcf artifact.tar .
60
+
61
+ - name: Upload documentation
62
+ uses: actions/upload-artifact@v3
63
+ with:
64
+ name: github-pages
65
+ path: ./artifact.tar
66
+
67
+ # Deploy the artifact to GitHub pages.
68
+ # This is a separate job so that only actions/deploy-pages has the necessary permissions.
69
+ deploy:
70
+ needs: build
71
+ runs-on: ubuntu-latest
72
+ permissions:
73
+ pages: write
74
+ id-token: write
75
+ environment:
76
+ name: github-pages
77
+ url: ${{ steps.deployment.outputs.page_url }}
78
+ steps:
79
+ - id: deployment
80
+ uses: actions/deploy-pages@v1
.gitignore ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+
5
+ # C extensions
6
+ *.so
7
+
8
+ # Distribution / packaging
9
+ .Python
10
+ env/
11
+ .venv
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+
27
+ # PyInstaller
28
+ # Usually these files are written by a python script from a template
29
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
30
+ *.manifest
31
+ *.spec
32
+
33
+ # Installer logs
34
+ pip-log.txt
35
+ pip-delete-this-directory.txt
36
+
37
+ # Unit test / coverage reports
38
+ htmlcov/
39
+ .tox/
40
+ .coverage
41
+ .coverage.*
42
+ .cache
43
+ nosetests.xml
44
+ coverage.xml
45
+ *.cover
46
+
47
+ # Translations
48
+ *.mo
49
+ *.pot
50
+
51
+ # Django stuff:
52
+ *.log
53
+
54
+ # Sphinx documentation
55
+ docs/_build/
56
+
57
+ # PyBuilder
58
+ target/
59
+
60
+ # DotEnv configuration
61
+ .env
62
+
63
+ # Database
64
+ *.db
65
+ *.rdb
66
+
67
+ # Pycharm
68
+ .idea
69
+
70
+ # VS Code
71
+ .vscode/
72
+
73
+ # Spyder
74
+ .spyproject/
75
+
76
+ # Jupyter NB Checkpoints
77
+ .ipynb_checkpoints/
78
+
79
+ # Mac OS-specific storage files
80
+ .DS_Store
81
+
82
+ # vim
83
+ *.swp
84
+ *.swo
85
+
86
+ # Mypy cache
87
+ .mypy_cache/
88
+
89
+ # pytest cache
90
+ .pytest_cache/
91
+
92
+ # Checkpoints
93
+ checkpoint-*
94
+
95
+ # Documentation
96
+ docs/mumin/
97
+ docs/index.html
98
+ docs/mumin.html
99
+ docs/search.json
100
+
101
+ # Testing
102
+ mumin-*.zip
103
+ test.py
104
+
105
+ # Data
106
+ data/*
.pre-commit-config.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/ambv/black
3
+ rev: 22.3.0
4
+ hooks:
5
+ - id: black
6
+ - repo: https://github.com/timothycrosley/isort
7
+ rev: 5.7.0
8
+ hooks:
9
+ - id: isort
10
+ - repo: https://gitlab.com/pycqa/flake8
11
+ rev: 3.8.4
12
+ hooks:
13
+ - id: flake8
14
+ - repo: https://github.com/kynan/nbstripout
15
+ rev: 0.5.0
16
+ hooks:
17
+ - id: nbstripout
18
+ - repo: https://github.com/pre-commit/mirrors-mypy
19
+ rev: v0.782
20
+ hooks:
21
+ - id: mypy
22
+ args: [--ignore-missing-imports]
CHANGELOG.md ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on
6
+ [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
7
+ and this project adheres to
8
+ [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
9
+
10
+
11
+ ## [v1.10.0] - 2022-07-31
12
+ ### Added
13
+ - Added `n_jobs` and `chunksize` arguments to `MuminDataset`, to enable customisation
14
+ of these.
15
+
16
+ ### Changed
17
+ - Lowered the default value of `chunksize` from 50 to 10, which also lowers the memory
18
+ requirements when processing articles and images, as fewer of these are kept in
19
+ memory at a time.
20
+ - Now stores all images as `uint8` NumPy arrays rather than `int64`, reducing memory
21
+ usage of images significantly.
22
+
23
+
24
+ ## [v1.9.0] - 2022-07-22
25
+ ### Added
26
+ - Added checkpoint after rehydration. This means that if compilation fails for whatever
27
+ reason after this point, the next compilation will resume after the rehydration
28
+ process.
29
+ - Added some more unit tests.
30
+
31
+ ### Fixed
32
+ - Fixed bug on Windows where some tweet IDs were negative.
33
+ - Fixed another bug on Windows where the timeout decorator did not work, due to the use
34
+ of signals, which are not available on Windows machines.
35
+ - Fixed bug on MacOS causing Python to crash during parallel extraction of articles and
36
+ images.
37
+
38
+ ### Changed
39
+ - Refactored repository to use the more modern `pyproject.toml` with `poetry`.
40
+
41
+
42
+ ## [v1.8.0] - 2022-04-14
43
+ ### Changed
44
+ - Now allows instantiation of `MuminDataset` without having any Twitter bearer
45
+ token, neither as an explicit argument nor as an environment variable, which
46
+ is useful for pre-compiled datasets. If the dataset needs to be compiled then
47
+ a `RuntimeError` will be raised when calling the `compile` method.
48
+
49
+
50
+ ## [v1.7.0] - 2022-03-24
51
+ ### Added
52
+ - Now allows setting `twitter_bearer_token=None` in the constructor of
53
+ `MuminDataset`, which uses the environment variable `TWITTER_API_KEY`
54
+ instead, which can be stored in a separate `.env` file. This is now the
55
+ default value of `twitter_bearer_token`.
56
+
57
+ ### Changed
58
+ - Replaced `DataFrame.append` calls with `pd.concat`, as the former is
59
+ deprecated and will be removed from `pandas` in the future.
60
+
61
+
62
+ ## [v1.6.2] - 2022-03-21
63
+ ### Fixed
64
+ - Now removes claims that are only connected to deleted tweets when calling
65
+ `to_dgl`. This previously caused a bug that was due to a mismatch between
66
+ nodes in the dataset (which includes deleted ones) and nodes in the DGL graph
67
+ (which does not contain the deleted ones).
68
+
69
+
70
+ ## [v1.6.1] - 2022-03-17
71
+ ### Fixed
72
+ - Now correctly catches JSONDecodeError during rehydration.
73
+
74
+
75
+ ## [v1.6.0] - 2022-03-10
76
+ ### Changed
77
+ - Changed the download link from Git-LFS to the official data.bris data
78
+ repository, with URI
79
+ [https://doi.org/10.5523/bris.23yv276we2mll25fjakkfim2ml](https://doi.org/10.5523/bris.23yv276we2mll25fjakkfim2ml).
80
+
81
+
82
+ ## [v1.5.0] - 2022-02-19
83
+ ### Changed
84
+ - Now using dicts rather than Series in `to_dgl`. This improved the wall time
85
+ from 1.5 hours to 2 seconds!
86
+
87
+ ### Fixed
88
+ - There was a bug in the call to `dgl.data.utils.load_graphs` causing
89
+ `load_dgl_graph` to fail. This is fixed now.
90
+
91
+
92
+ ## [v1.4.1] - 2022-02-19
93
+ ### Changed
94
+ - Now only saves dataset at the end of `add_embeddings` if any embeddings were
95
+ added.
96
+
97
+
98
+ ## [v1.4.0] - 2022-02-19
99
+ ### Added
100
+ - The `to_dgl` method is now being parallelised, speeding export up
101
+ significantly.
102
+ - Added convenience functions `save_dgl_graph` and `load_dgl_graph`, which
103
+ stores the Boolean train/val/test masks as unsigned 8-bit integers and
104
+ handles the conversion. Using the `dgl`-native `save_graphs` and
105
+ `load_graphs` causes an error, as it cannot handle Boolean tensors. These two
106
+ convenience functions can be loaded simply as
107
+ `from mumin import save_dgl_graph, load_dgl_graph`.
108
+
109
+
110
+ ## [v1.3.0] - 2022-02-18
111
+ ### Added
112
+ - Now uses GPU to embed all the text and images, if available.
113
+
114
+
115
+ ## [v1.2.5] - 2022-02-06
116
+ ### Fixed
117
+ - Now does not raise an error if we are not authorised to rehydrate a tweet,
118
+ and instead merely skips it.
119
+
120
+
121
+ ## [v1.2.4] - 2022-01-24
122
+ ### Fixed
123
+ - Changed the minimum Python version compatible with `mumin` to 3.7, rather
124
+ than 3.4.
125
+
126
+
127
+ ## [v1.2.3] - 2021-12-15
128
+ ### Fixed
129
+ - During rehydration, the authors of the source tweets were not included, and
130
+ the images from tweets were not included either. They are now included.
131
+
132
+
133
+ ## [v1.2.2] - 2021-12-15
134
+ ### Fixed
135
+ - Now replacing NaN values for Numpy features with `np.nan` instead of an
136
+ array, as `fillna` does not accept that. These are then converted in a scalar
137
+ array with a `np.nan` value.
138
+
139
+
140
+ ## [v1.2.1] - 2021-12-15
141
+ ### Fixed
142
+ - When running `add_embeddings`, only embeddings to existing nodes will be
143
+ added. This caused an error when e.g. images were not included in the
144
+ dataset.
145
+
146
+
147
+ ## [v1.2.0] - 2021-12-14
148
+ ### Changed
149
+ - If tweets have been deleted (and thus cannot be rehydrated) then we keep them
150
+ along with their related entities, just without being able to populate their
151
+ features. When exporting to DGL then neither these tweets nor their replies
152
+ are included.
153
+
154
+ ### Added
155
+ - Now includes a check that tweets are actually rehydrated, and raises an error
156
+ if they are not. Such an error is usually due to the inputted Twitter Bearer
157
+ Token being invalid.
158
+
159
+
160
+ ## [v1.1.1] - 2021-12-13
161
+ ### Fixed
162
+ - Fixed bug in producing embeddings
163
+
164
+
165
+ ## [v1.1.0] - 2021-12-12
166
+ ### Fixed
167
+ - Updated the dataset with deduplicated entries. The deduplication is done such
168
+ that the duplicate with the largest `relevance` parameter is kept.
169
+ - Include checks of whether nodes and relations exist, before extracting data
170
+ from them.
171
+
172
+ ### Added
173
+ - Added `include_timelines` option, which allows one to not include all the
174
+ extra tweets in the timelines if not needed. As this greatly increases the
175
+ amount of tweets needed to rehydrate, it defaults to False.
176
+
177
+
178
+ ## [v1.0.2] - 2021-12-09
179
+ ### Fixed
180
+ - Removed the relations from the dump which we are getting through compilation
181
+ anyway.
182
+ - Updated the filtering mechanism, so that the `relevance` parameter is built
183
+ in to all nodes and relations upon download.
184
+ - Deal with the situation where no relations exist of a certain type, above a
185
+ specified threshold.
186
+
187
+
188
+ ## [v1.0.1] - 2021-12-05
189
+ ### Fixed
190
+ - Added in the `POSTED` relation, as leaving this out effectively meant that
191
+ all the new tweets were filtered out during compilation.
192
+
193
+
194
+ ## [v1.0.0] - 2021-12-03
195
+ ### Changed
196
+ - Added new version of the dataset, which now includes a sample of ~100
197
+ timeline tweets for every user. This approximately doubles the dataset size,
198
+ to ~200MB before compilation. This new dataset includes different
199
+ train/val/test splits as well, which is now 80/10/10 rather than 60/10/30.
200
+ This means that the training dataset will see a much more varied amount of
201
+ events (6-7) compared to the previous 2.
202
+
203
+
204
+ ## [v0.7.0] - 2021-12-02
205
+ ### Changed
206
+ - Changed `include_images` to `include_tweet_images`, which now only includes
207
+ the images from the tweets themselves. Further, `include_user_images` is
208
+ changed to `include_extra_images`, which now includes both profile pictures
209
+ and the top images from articles. The tweet pictures are included by default,
210
+ and the extras are not. This is to reduce the size of the default dataset, to
211
+ make it easier to use.
212
+
213
+
214
+ ## [v0.6.0] - 2021-12-01
215
+ ### Changed
216
+ - Split up the `include_images` into `include_images` and
217
+ `include_user_images`, with the former including images from tweets and
218
+ articles, and the latter being profile pictures. The former has been set to
219
+ True by default, and the latter False. This is due to the large amount of
220
+ profile pictures making the dataset excessively large.
221
+
222
+ ### Fixed
223
+ - Now catches connection errors when attempting to rehydrate tweets.
224
+
225
+
226
+ ## [v0.5.3] - 2021-11-26
227
+ ### Fixed
228
+ - Masks have been changed to boolean tensors, as otherwise indexing did not
229
+ work properly.
230
+ - In the case where a claim/tweet does not have any label, this produces NaN
231
+ values in the mask- and label tensors. These are now substituted for zeroes.
232
+ This means that they will always be masked out, and so the label will not
233
+ matter anyway.
234
+
235
+
236
+ ## [v0.5.2] - 2021-11-24
237
+ ### Fixed
238
+ - Now converting masks to long tensors, which is required for them to be used
239
+ as indexing tensors in PyTorch.
240
+
241
+ ### Changed
242
+ - Now only dumping dataset once while adding embeddings, where previously it
243
+ dumped the dataset after adding embeddings to each node type. This is done to
244
+ add embeddings faster, as the dumping of the dataset can take quite a long
245
+ time.
246
+ - Now blanket catching all errors when processing images and articles, as there
247
+ were too many edge cases.
248
+
249
+
250
+ ## [v0.5.1] - 2021-11-09
251
+ ### Fixed
252
+ - When encountering HTTP status 401 (unauthorized) during rehydration, we skip
253
+ that batch of tweets.
254
+ - Image relations were extracted incorrectly, due to a wrong treatment of the
255
+ images coming directly from the tweets via the `media_key` identifier, and
256
+ the images coming from URLs present in the tweets themselves. Both are now
257
+ correctly included in a uniform fashion.
258
+ - Datatypes are now only set for a given node if the node is included in the
259
+ dataset. For instance, datatypes for the article features are only set if
260
+ `include_articles == True`.
261
+
262
+
263
+ ## [v0.5.0] - 2021-11-08
264
+ ### Added
265
+ - The `Claim` nodes now have `language`, `keywords`, `cluster_keywords` and
266
+ `cluster` attributes.
267
+ - Now sets datatypes for all the dataframes, to reduce memory usage.
268
+
269
+ ### Fixed
270
+ - Updated `README` to a single zip file, rather than stating that the dataset
271
+ is saved as a bunch of CSV files.
272
+ - Fixed image embedding shape from (1, 768) to (768,).
273
+ - Article embeddings are now computed correctly.
274
+ - Catch `IndexError` and `LocationParseError` when processing images.
275
+
276
+ ### Changed
277
+ - Now dumping files incrementally rather than keeping all of them in memory, to
278
+ avoid out-of-memory issues when saving the dataset.
279
+ - Dataset `size` argument now defaults to 'small', rather than 'large'.
280
+ - Updated the dataset. This is still not the final version: timelines of users
281
+ are currently missing.
282
+ - Now storing the dataset in a zip file of Pickle files instead of HDF. This is
283
+ because of HDF requiring extra installation, and there being maximal storage
284
+ requirements in the dataframes when storing as HDF. The resulting zip file of
285
+ Pickle files is stored with protocol 4, making it compatible with Python 3.4
286
+ and newer. Further, the dataset being downloaded has been heavily compressed,
287
+ taking up a quarter of the disk space compared to the previous CSV approach.
288
+ When the dataset has been downloaded it will be converted to a less
289
+ compressed version, taking up more space but making loading and saving much
290
+ faster.
291
+
292
+ ### Removed
293
+ - Disabled `numexpr`, `transformers` and `bs4` logging.
294
+
295
+
296
+ ## [v0.4.0] - 2021-10-26
297
+ ### Fixed
298
+ - All embeddings are now extracted from the pooler output, corresponding to the
299
+ `[CLS]` tag.
300
+ - Ensured that train/val/test masks are boolean tensors when exporting to DGL,
301
+ as opposed to binary integers.
302
+ - Content embeddings for articles were not aggregated per chunk, but now a mean
303
+ is taken across all content chunks.
304
+ - Assign zero embeddings to user descriptions if they are not available.
305
+
306
+ ### Changed
307
+ - The DGL graph returned by the `to_dgl` method now returns a bidirectional
308
+ graph.
309
+ - The `verbose` argument of `MuminDataset` now defaults to `True`.
310
+ - Now storing the dataset as a single HDF file instead of a zipped folder of
311
+ CSV files, primarily because data types are being preserved in this way, and
312
+ that HDF is a binary format supported by Pandas which can handle
313
+ multidimensional ndarrays as entries in a dataframe.
314
+ - The default models used to embed texts and images are now `xlm-roberta-base`
315
+ and `google/vit-base-patch16-224-in21k`.
316
+
317
+ ### Removed
318
+ - Removed the `poll` and `place` nodes, as they were too few to matter.
319
+ - Removed the `(:User)-[:HAS_PINNED]->(:Tweet)` relation, as there were too few
320
+ of them to matter.
321
+
322
+
323
+ ## [v0.3.1] - 2021-10-19
324
+ ### Fixed
325
+ - Fixed the shape of the user description embeddings.
326
+
327
+
328
+ ## [v0.3.0] - 2021-10-18
329
+ ### Fixed
330
+ - Now catches `SSLError` and `OSError` when processing images.
331
+ - Now catches `ReadTimeoutError` when processing articles.
332
+ - The `(:Tweet)-[:MENTIONS]->(:User)` was missing in the dataset. It has now
333
+ been added back in.
334
+ - Added tokenizer truncation when adding node embeddings.
335
+ - Fixed an issue with embedding user descriptions when the description is not
336
+ available.
337
+
338
+ ### Changed
339
+ - Changed the download link to the dataset, which now fetches the dataset from
340
+ a specific commit, enabling proper dataset versioning.
341
+ - Changed the timeout parameter when downloading images from five seconds to
342
+ ten seconds.
343
+ - Now processing 50 articles and images on each worker, compared to the
344
+ previous 5.
345
+ - When loading in an existing dataset, auxilliaries and islands are removed.
346
+ This ensures that `to_dgl` works properly.
347
+
348
+ ### Removed
349
+ - Removed the review warning from the `README` and when initialising the
350
+ dataset. The dataset is still not complete, in the sense that we will add
351
+ retweets and timelines, but we will instead just keep versioning the dataset
352
+ until we have included these extra features.
353
+
354
+
355
+ ## [v0.2.0] - 2021-10-12
356
+ ### Added
357
+ - Added claim embeddings to Claim nodes, being the transformer embeddings of
358
+ the claims translated to English, as described in the paper.
359
+ - Added train/val/test split to claim nodes. When exporting to DGL using the
360
+ `to_dgl` method, the Claim and Tweet nodes will have `train_mask`, `val_mask`
361
+ and `test_mask` attributes that can be used to control loss and metric
362
+ calculation. These are consistent, meaning that tweets connected to claims
363
+ will always belong to the same split.
364
+ - Added labels to both Tweet and Claim nodes.
365
+
366
+ ### Fixed
367
+ - Properly embeds reviewers of claims in case a claim has been reviewed by
368
+ multiple reviewers.
369
+ - Load claim embeddings properly.
370
+ - Catches `TooManyRequests` exception when extracting images.
371
+ - Load dataset CSVs with Python engine, as the C engine caused errors.
372
+ - Disable tokenizer parallelism, which caused warning messages during
373
+ rehydration of tweets.
374
+ - Ensure proper quoting of strings when dumping dataset to CSVs.
375
+ - Enable truncation of strings before tokenizing, when embedding texts.
376
+ - Convert masks to integers, which caused an issue when exporting to a DGL
377
+ graph.
378
+ - Bug when computing reviewer embeddings for claims.
379
+ - Now properly shows `compiled=True` when printing the dataset, after
380
+ compilation.
381
+
382
+ ### Changed
383
+ - Changed disclaimer about review period.
384
+
385
+
386
+ ## [v0.1.4] - 2021-09-13
387
+ ### Fixed
388
+ - Include `(:User)-[:POSTED]->(:Reply)` in the dataset, extracted from the
389
+ rehydrated reply and quote tweets.
390
+
391
+
392
+ ## [v0.1.3] - 2021-09-13
393
+ ### Fixed
394
+ - Compilation error when including images.
395
+ - Only include videos if they are present in the dataset.
396
+ - Ensure that article embeddings can properly be converted to PyTorch tensors
397
+ when exporting to DGL.
398
+
399
+
400
+ ## [v0.1.2] - 2021-09-13
401
+ ### Fixed
402
+ - The replies were not reduced correctly when the `small` or `medium` variants
403
+ of the dataset was compiled.
404
+ - The reply features were not filtered and renamed properly, to keep them
405
+ consistent with the tweet nodes.
406
+ - Users without any description now gets assigned a zero vector as their
407
+ description embedding.
408
+ - If a relation does not have any node pairs then do not try to create a
409
+ corresponding DGL relation.
410
+ - Reset `nodes` and `rels` attributes when loading dataset.
411
+ - Add embeddings for `Reply` nodes.
412
+
413
+
414
+ ## [v0.1.1] - 2021-09-08
415
+ ### Changed
416
+ - Changed installation instructions in readme to `pip install mumin`.
417
+
418
+
419
+ ## [v0.1.0] - 2021-09-07
420
+ ### Added
421
+ - First release, including a `MuminDataset` class that can compile the dataset
422
+ dump the compiled dataset to local `csv` files, and export it as a `dgl`
423
+ graph.
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021-2022 CLARITI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MuMiN-Build
2
+ This repository contains the package used to build the MuMiN dataset from the
3
+ paper [Nielsen and McConville: _MuMiN: A Large-Scale Multilingual Multimodal
4
+ Fact-Checked Misinformation Social Network Dataset_
5
+ (2021)](https://arxiv.org/abs/2202.11684).
6
+
7
+ See [the MuMiN website](https://mumin-dataset.github.io/) for more information,
8
+ including a leaderboard of the top performing models.
9
+
10
+ ______________________________________________________________________
11
+ [![PyPI Status](https://badge.fury.io/py/mumin.svg)](https://pypi.org/project/mumin/)
12
+ [![Documentation](https://img.shields.io/badge/docs-passing-green)](https://mumin-dataset.github.io/mumin-build/mumin.html)
13
+ [![License](https://img.shields.io/github/license/mumin-dataset/mumin-build)](https://github.com/mumin-dataset/mumin-build/blob/main/LICENSE)
14
+ [![LastCommit](https://img.shields.io/github/last-commit/mumin-dataset/mumin-build)](https://github.com/mumin-dataset/mumin-build/commits/main)
15
+ [![Code Coverage](https://img.shields.io/badge/Coverage-76%25-yellowgreen.svg)](https://github.com/mumin-dataset/mumin-build/tree/dev/tests)
16
+
17
+
18
+ ## Installation
19
+ The `mumin` package can be installed using `pip`:
20
+ ```
21
+ $ pip install mumin
22
+ ```
23
+
24
+ To be able to build the dataset, Twitter data needs to be downloaded, which
25
+ requires a Twitter API key. You can get one
26
+ [for free here](https://developer.twitter.com/en/portal/dashboard). You will
27
+ need the _Bearer Token_.
28
+
29
+
30
+ ## Quickstart
31
+ The main class of the package is the `MuminDataset` class:
32
+ ```
33
+ >>> from mumin import MuminDataset
34
+ >>> dataset = MuminDataset(twitter_bearer_token=XXXXX)
35
+ >>> dataset
36
+ MuminDataset(size='small', compiled=False)
37
+ ```
38
+
39
+ By default, this loads the small version of the dataset. This can be changed by
40
+ setting the `size` argument of `MuminDataset` to one of 'small', 'medium' or
41
+ 'large'. To begin using the dataset, it first needs to be compiled. This will
42
+ download the dataset, rehydrate the tweets and users, and download all the
43
+ associated news articles, images and videos. This usually takes a while.
44
+ ```
45
+ >>> dataset.compile()
46
+ MuminDataset(num_nodes=388,149, num_relations=475,490, size='small', compiled=True)
47
+ ```
48
+
49
+ Note that this dataset does not contain _all_ the nodes and relations in
50
+ MuMiN-small, as that would take way longer to compile. The data left out are
51
+ timelines, profile pictures and article images. These can be included by
52
+ specifying `include_extra_images=True` and/or `include_timelines=True` in the
53
+ constructor of `MuminDataset`.
54
+
55
+ After compilation, the dataset can also be found in the `mumin-<size>.zip`
56
+ file. This file name can be changed using the `dataset_path` argument when
57
+ initialising the `MuminDataset` class. If you need embeddings of the nodes, for
58
+ instance for use in machine learning models, then you can simply call the
59
+ `add_embeddings` method:
60
+ ```
61
+ >>> dataset.add_embeddings()
62
+ MuminDataset(num_nodes=388,149, num_relations=475,490, size='small', compiled=True)
63
+ ```
64
+
65
+ **Note**: If you need to use the `add_embeddings` method, you need to install
66
+ the `mumin` package as either `pip install mumin[embeddings]` or `pip install
67
+ mumin[all]`, which will install the `transformers` and `torch` libraries. This
68
+ is to ensure that such large libraries are only downloaded if needed.
69
+
70
+ It is possible to export the dataset to the
71
+ [Deep Graph Library](https://www.dgl.ai/), using the `to_dgl` method:
72
+ ```
73
+ >>> dgl_graph = dataset.to_dgl()
74
+ >>> type(dgl_graph)
75
+ dgl.heterograph.DGLHeteroGraph
76
+ ```
77
+
78
+ **Note**: If you need to use the `to_dgl` method, you need to install the
79
+ `mumin` package as `pip install mumin[dgl]` or `pip install mumin[all]`, which
80
+ will install the `dgl` and `torch` libraries.
81
+
82
+ For a more in-depth tutorial of how to work with the dataset, including
83
+ training multiple different misinformation classifiers, see [the
84
+ tutorial](https://colab.research.google.com/drive/1Kz0EQtySYQTo1ui8F2KZ6ERneZVf5TIN).
85
+
86
+
87
+ ## Dataset Statistics
88
+
89
+ | Dataset | #Claims | #Threads | #Tweets | #Users | #Articles | #Images | #Languages | %Misinfo |
90
+ | ---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
91
+ | MuMiN-large | 12,914 | 26,048 | 21,565,018 | 1,986,354 | 10,920 | 6,573 | 41 | 94.57% |
92
+ | MuMiN-medium | 5,565 | 10,832 | 12,650,371 | 1,150,259 | 4,212 | 2,510 | 37 | 94.07% |
93
+ | MuMiN-small | 2,183 | 4,344 | 7,202,506 | 639,559 | 1,497 | 1,036 | 35 | 92.87% |
94
+
95
+
96
+ ## Related Repositories
97
+ - [MuMiN website](https://mumin-dataset.github.io/), the central place for the
98
+ MuMiN ecosystem, containing tutorials, leaderboards and links to the paper
99
+ and related repositories.
100
+ - [MuMiN](https://github.com/MuMiN-dataset/mumin), containing the
101
+ paper in PDF and LaTeX form.
102
+ - [MuMiN-trawl](https://github.com/MuMiN-dataset/mumin-trawl),
103
+ containing the source code used to construct the dataset from scratch.
104
+ - [MuMiN-baseline](https://github.com/MuMiN-dataset/mumin-baseline),
105
+ containing the source code for the baselines.
makefile ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This ensures that we can call `make <target>` even if `<target>` exists as a file or
2
+ # directory.
3
+ .PHONY: notebook docs
4
+
5
+ # Exports all variables defined in the makefile available to scripts
6
+ .EXPORT_ALL_VARIABLES:
7
+
8
+ install-poetry:
9
+ @echo "Installing poetry..."
10
+ @curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 -
11
+
12
+ uninstall-poetry:
13
+ @echo "Uninstalling poetry..."
14
+ @curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 - --uninstall
15
+
16
+ install:
17
+ @echo "Installing..."
18
+ @if [ "$(shell which poetry)" = "" ]; then \
19
+ make install-poetry; \
20
+ fi
21
+ @if [ "$(shell which gpg)" = "" ]; then \
22
+ echo "GPG not installed, so an error will occur. Install GPG on MacOS with "\
23
+ "`brew install gnupg` or on Ubuntu with `apt install gnupg` and run "\
24
+ "`make install` again."; \
25
+ fi
26
+ @poetry env use python3
27
+ @poetry run python3 -m src.scripts.fix_dot_env_file
28
+ @git init
29
+ @. .env; \
30
+ git config --local user.name "$${GIT_NAME}"; \
31
+ git config --local user.email "$${GIT_EMAIL}"
32
+ @. .env; \
33
+ if [ "$${GPG_KEY_ID}" = "" ]; then \
34
+ echo "No GPG key ID specified. Skipping GPG signing."; \
35
+ git config --local commit.gpgsign false; \
36
+ else \
37
+ echo "Signing with GPG key ID $${GPG_KEY_ID}..."; \
38
+ git config --local commit.gpgsign true; \
39
+ git config --local user.signingkey "$${GPG_KEY_ID}"; \
40
+ fi
41
+ @poetry install
42
+ @poetry run pre-commit install
43
+
44
+ remove-env:
45
+ @poetry env remove python3
46
+ @echo "Removed virtual environment."
47
+
48
+ docs:
49
+ @poetry run pdoc --docformat google -o docs src/mumin
50
+ @echo "Saved documentation."
51
+
52
+ view-docs:
53
+ @echo "Viewing API documentation..."
54
+ @open docs/mumin.html
55
+
56
+ clean:
57
+ @find . -type f -name "*.py[co]" -delete
58
+ @find . -type d -name "__pycache__" -delete
59
+ @rm -rf .pytest_cache
60
+ @echo "Cleaned repository."
61
+
62
+ test:
63
+ @pytest && readme-cov
64
+
65
+ tree:
66
+ @tree -a \
67
+ -I .git \
68
+ -I .mypy_cache . \
69
+ -I .env \
70
+ -I .venv \
71
+ -I poetry.lock \
72
+ -I .ipynb_checkpoints \
73
+ -I dist \
74
+ -I .gitkeep \
75
+ -I docs \
76
+ -I .pytest_cache
77
+
78
+ bump-major:
79
+ @poetry run python -m src.scripts.versioning --major
80
+ @echo "Bumped major version."
81
+
82
+ bump-minor:
83
+ @poetry run python -m src.scripts.versioning --minor
84
+ @echo "Bumped minor version."
85
+
86
+ bump-patch:
87
+ @poetry run python -m src.scripts.versioning --patch
88
+ @echo "Bumped patch version."
89
+
90
+ publish:
91
+ @. .env; \
92
+ printf "Preparing to publish to PyPI. Have you ensured to change the package version with 'make bump-X' for 'X' being 'major', 'minor' or 'patch', as well as run unit tests with 'make test'? [y/n] : "; \
93
+ read -r answer; \
94
+ if [ "$${answer}" = "y" ]; then \
95
+ if [ "$${PYPI_API_TOKEN}" = "" ]; then \
96
+ echo "No PyPI API token specified in the '.env' file, so cannot publish."; \
97
+ else \
98
+ echo "Publishing to PyPI..."; \
99
+ poetry publish --build --username "__token__" --password "$${PYPI_API_TOKEN}"; \
100
+ echo "Published!"; \
101
+ fi \
102
+ else \
103
+ echo "Publishing aborted."; \
104
+ fi
105
+
106
+ compile-small:
107
+ @poetry run python -m src.scripts.compile_mumin small
108
+
109
+ compile-medium:
110
+ @poetry run python -m src.scripts.compile_mumin medium
111
+
112
+ compile-large:
113
+ @poetry run python -m src.scripts.compile_mumin large
114
+
115
+ compile-test:
116
+ @poetry run python -m src.scripts.compile_mumin test
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
poetry.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [virtualenvs]
2
+ create = true
3
+ in-project = true
pyproject.toml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["poetry-core>=1.0.0"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [tool.poetry]
6
+ name = "mumin"
7
+ version = "1.10.0"
8
+ description = "Seamlessly build the MuMiN dataset."
9
+ authors = [
10
+ "Dan Saattrup Nielsen <dan.nielsen@alexandra.dk>",
11
+ "Ryan McConville <ryan.mcconville@bristol.ac.uk>",
12
+ ]
13
+ readme = "README.md"
14
+ license = "MIT"
15
+ homepage = "https://mumin-dataset.github.io/"
16
+ repository = "https://github.com/MuMiN-dataset/mumin-build"
17
+
18
+ [tool.poetry.dependencies]
19
+ python = ">=3.8,<3.11"
20
+ tqdm = "^4.62.0"
21
+ transformers = "^4.20.0"
22
+ torch = "^1.12.0"
23
+ newspaper3k = "^0.2.8"
24
+ pandas = "^1.4.3"
25
+ python-dotenv = "^0.20.0"
26
+ wrapt-timeout-decorator = "^1.3.12"
27
+
28
+ [tool.poetry.dev-dependencies]
29
+ pdoc = "^7.1.1"
30
+ pytest = "^6.2.5"
31
+ pre-commit = "^2.17.0"
32
+ black = "^22.3.0"
33
+ isort = "^5.10.1"
34
+ pytest-xdist = "^2.5.0"
35
+ pytest-cov = "^3.0.0"
36
+ readme-coverage-badger = "^0.1.2"
37
+ python-dotenv = "^0.20.0"
38
+
39
+ [tool.pytest.ini_options]
40
+ minversion = "6.0"
41
+ addopts = [
42
+ '--verbose',
43
+ '--durations=10',
44
+ '--color=yes',
45
+ '-s',
46
+ '-vv',
47
+ '--doctest-modules',
48
+ '--cov=src/mumin',
49
+ '-n 1',
50
+ ]
51
+ xfail_strict = true
52
+ filterwarnings = ["error"]
53
+ log_cli_level = "info"
54
+ testpaths = ["tests", "src/mumin"]
55
+
56
+ [tool.black]
57
+ line-length = 88
58
+ include = '\.pyi?$'
59
+ exclude = '''
60
+ /(
61
+ \.git
62
+ | \.hg
63
+ | \.mypy_cache
64
+ | \.tox
65
+ | \.venv
66
+ | _build
67
+ | buck-out
68
+ | build
69
+ )/
70
+ '''
71
+
72
+ [tool.isort]
73
+ profile = "black"
src/mumin/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. include:: ../../README.md
3
+ """
4
+
5
+ import logging
6
+
7
+ import pkg_resources # noqa: E402
8
+
9
+ # Set up logging
10
+ fmt = "%(asctime)s [%(levelname)s] %(message)s"
11
+ logging.basicConfig(level=logging.INFO, format=fmt)
12
+ logging.getLogger("urllib3").disabled = True
13
+ logging.getLogger("urllib3").propagate = False
14
+ logging.getLogger("newspaper").disabled = True
15
+ logging.getLogger("newspaper").propagate = False
16
+ logging.getLogger("jieba").disabled = True
17
+ logging.getLogger("jieba").propagate = False
18
+ logging.getLogger("numexpr").disabled = True
19
+ logging.getLogger("numexpr").propagate = False
20
+ logging.getLogger("bs4").disabled = True
21
+ logging.getLogger("bs4").propagate = False
22
+ logging.getLogger("transformers").disabled = True
23
+ logging.getLogger("transformers").propagate = False
24
+
25
+ from .dataset import MuminDataset # noqa
26
+ from .dgl import load_dgl_graph, save_dgl_graph # noqa
27
+
28
+ # Fetches the version of the package as defined in pyproject.toml
29
+ __version__ = pkg_resources.get_distribution("mumin").version
src/mumin/article.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to processing articles"""
2
+
3
+ import datetime as dt
4
+ import re
5
+ import warnings
6
+ from typing import Optional, Union
7
+
8
+ from newspaper import Article
9
+ from wrapt_timeout_decorator.wrapt_timeout_decorator import timeout
10
+
11
+
12
+ @timeout(10)
13
+ def download_article_with_timeout(article: Article):
14
+ with warnings.catch_warnings():
15
+ warnings.simplefilter("ignore", category=DeprecationWarning)
16
+ article.download()
17
+ return article
18
+
19
+
20
+ def process_article_url(url: str) -> Union[None, dict]:
21
+ """Process the URL and extract the article.
22
+
23
+ Args:
24
+ url (str): The URL.
25
+
26
+ Returns:
27
+ dict or None:
28
+ The processed article, or None if the URL could not be parsed.
29
+ """
30
+ # Remove GET arguments from the URL
31
+ stripped_url = re.sub(r'(\?.*"|\/$)', "", url)
32
+
33
+ try:
34
+ article = Article(stripped_url)
35
+ article = download_article_with_timeout(article)
36
+ article.parse()
37
+ except Exception: # noqa
38
+ return None
39
+
40
+ # Extract the title and skip URL if it is empty
41
+ title = article.title
42
+ if title == "":
43
+ return None
44
+ else:
45
+ title = re.sub("\n+", "\n", title)
46
+ title = re.sub(" +", " ", title)
47
+ title = title.strip()
48
+
49
+ # Extract the content and skip URL if it is empty
50
+ content = article.text.strip()
51
+ if content == "":
52
+ return None
53
+ else:
54
+ content = re.sub("\n+", "\n", content)
55
+ content = re.sub(" +", " ", content)
56
+ content = content.strip()
57
+
58
+ # Extract the authors, the publishing date and the top image
59
+ authors = list(article.authors)
60
+ publish_date: Optional[str]
61
+ if article.publish_date is not None:
62
+ date = article.publish_date
63
+ publish_date = dt.datetime.strftime(date, "%Y-%m-%d")
64
+ else:
65
+ publish_date = None
66
+ try:
67
+ top_image_url = article.top_image
68
+ except AttributeError:
69
+ top_image_url = None
70
+
71
+ data_dict = dict(
72
+ url=stripped_url,
73
+ title=title,
74
+ content=content,
75
+ authors=authors,
76
+ publish_date=publish_date,
77
+ top_image_url=top_image_url,
78
+ )
79
+ return data_dict
src/mumin/data_extractor.py ADDED
@@ -0,0 +1,1382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract node and relation data from the rehydrated Twitter data"""
2
+
3
+ import multiprocessing as mp
4
+ import re
5
+ from collections import defaultdict
6
+ from typing import Dict, List, Optional, Tuple, Union
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ from tqdm.auto import tqdm
11
+
12
+ from .article import process_article_url
13
+ from .image import process_image_url
14
+
15
+
16
+ class DataExtractor:
17
+ """Extract node and relation data from the rehydrated Twitter data.
18
+
19
+ Args:
20
+ include_replies (bool):
21
+ Whether to include replies.
22
+ include_articles (bool):
23
+ Whether to include articles.
24
+ include_tweet_images (bool):
25
+ Whether to include tweet images.
26
+ include_extra_images (bool):
27
+ Whether to include extra images.
28
+ include_hashtags (bool):
29
+ Whether to include hashtags.
30
+ include_mentions (bool):
31
+ Whether to include mentions.
32
+ n_jobs (int):
33
+ The number of parallel jobs to use.
34
+ chunksize (int):
35
+ The number of samples to process at a time.
36
+
37
+ Attributes:
38
+ include_replies (bool):
39
+ Whether to include replies.
40
+ include_articles (bool):
41
+ Whether to include articles.
42
+ include_tweet_images (bool):
43
+ Whether to include tweet images.
44
+ include_extra_images (bool):
45
+ Whether to include extra images.
46
+ include_hashtags (bool):
47
+ Whether to include hashtags.
48
+ include_mentions (bool):
49
+ Whether to include mentions.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ include_replies: bool,
55
+ include_articles: bool,
56
+ include_tweet_images: bool,
57
+ include_extra_images: bool,
58
+ include_hashtags: bool,
59
+ include_mentions: bool,
60
+ n_jobs: int,
61
+ chunksize: int,
62
+ ):
63
+ self.include_replies = include_replies
64
+ self.include_articles = include_articles
65
+ self.include_tweet_images = include_tweet_images
66
+ self.include_extra_images = include_extra_images
67
+ self.include_hashtags = include_hashtags
68
+ self.include_mentions = include_mentions
69
+ self.n_jobs = n_jobs
70
+ self.chunksize = chunksize
71
+
72
+ def extract_all(
73
+ self,
74
+ nodes: Dict[str, pd.DataFrame],
75
+ rels: Dict[Tuple[str, str, str], pd.DataFrame],
76
+ ) -> Tuple[dict, dict]:
77
+ """Extract all node and relation data.
78
+
79
+ Args:
80
+ nodes (Dict[str, pd.DataFrame]):
81
+ A dictionary of node dataframes.
82
+ rels (Dict[Tuple[str, str, str], pd.DataFrame]):
83
+ A dictionary of relation dataframes.
84
+
85
+ Returns:
86
+ pair of dicts:
87
+ A tuple of updated node and relation dictionaries.
88
+ """
89
+ # Extract data directly from the rehydrated data
90
+ nodes["hashtag"] = self._extract_hashtags(
91
+ tweet_df=nodes["tweet"], user_df=nodes["user"]
92
+ )
93
+ rels[("user", "posted", "tweet")] = self._extract_user_posted_tweet(
94
+ tweet_df=nodes["tweet"], user_df=nodes["user"]
95
+ )
96
+ rels[("user", "posted", "reply")] = self._extract_user_posted_reply(
97
+ reply_df=nodes["reply"], user_df=nodes["user"]
98
+ )
99
+ rels[("tweet", "mentions", "user")] = self._extract_tweet_mentions_user(
100
+ tweet_df=nodes["tweet"], user_df=nodes["user"]
101
+ )
102
+ rels[("user", "mentions", "user")] = self._extract_user_mentions_user(
103
+ user_df=nodes["user"]
104
+ )
105
+
106
+ # Extract data relying on hashtag data
107
+ rels[
108
+ ("tweet", "has_hashtag", "hashtag")
109
+ ] = self._extract_tweet_has_hashtag_hashtag(
110
+ tweet_df=nodes["tweet"], hashtag_df=nodes["hashtag"]
111
+ )
112
+ rels[
113
+ ("user", "has_hashtag", "hashtag")
114
+ ] = self._extract_user_has_hashtag_hashtag(
115
+ user_df=nodes["user"], hashtag_df=nodes["hashtag"]
116
+ )
117
+
118
+ # Extract data relying on the pre-extracted article and image data, as well has
119
+ # the (:User)-[:POSTED]->(:Tweet) relation
120
+ nodes["url"] = self._extract_urls(
121
+ tweet_dicusses_claim_df=rels[("tweet", "discusses", "claim")],
122
+ user_posted_tweet_df=rels[("user", "posted", "tweet")],
123
+ user_df=nodes["user"],
124
+ tweet_df=nodes["tweet"],
125
+ article_df=nodes.get("article"),
126
+ image_df=nodes.get("image"),
127
+ )
128
+
129
+ # Extract data relying on the URL data without the URLs from the articles
130
+ nodes["article"] = self._extract_articles(
131
+ url_df=nodes["url"],
132
+ )
133
+
134
+ # Update the URLs with URLs from the articles
135
+ nodes["url"] = self._update_urls_from_articles(
136
+ url_df=nodes["url"], article_df=nodes["article"]
137
+ )
138
+
139
+ # Extract data relying on url data
140
+ rels[("user", "has_url", "url")] = self._extract_user_has_url_url(
141
+ user_df=nodes["user"], url_df=nodes["url"]
142
+ )
143
+ rels[
144
+ ("user", "has_profile_picture_url", "url")
145
+ ] = self._extract_user_has_profile_picture_url_url(
146
+ user_df=nodes["user"], url_df=nodes["url"]
147
+ )
148
+
149
+ # Extract data relying on url and pre-extracted image data
150
+ rels[("tweet", "has_url", "url")] = self._extract_tweet_has_url_url(
151
+ tweet_df=nodes["tweet"], url_df=nodes["url"], image_df=nodes.get("image")
152
+ )
153
+
154
+ # Extract data relying on article and url data
155
+ nodes["image"] = self._extract_images(
156
+ url_df=nodes["url"], article_df=nodes["article"]
157
+ )
158
+ rels[
159
+ ("article", "has_top_image_url", "url")
160
+ ] = self._extract_article_has_top_image_url_url(
161
+ article_df=nodes["article"], url_df=nodes["url"]
162
+ )
163
+
164
+ # Extract data relying on article and url data, as well has the
165
+ # (:Tweet)-[:HAS_URL]->(:Url) relation
166
+ rels[
167
+ ("tweet", "has_article", "article")
168
+ ] = self._extract_tweet_has_article_article(
169
+ tweet_has_url_url_df=rels[("tweet", "has_url", "url")],
170
+ article_df=nodes["article"],
171
+ url_df=nodes["url"],
172
+ )
173
+
174
+ # Extract data relying on image and url data, as well has the
175
+ # (:Tweet)-[:HAS_URL]->(:Url) relation
176
+ rels[("tweet", "has_image", "image")] = self._extract_tweet_has_image_image(
177
+ tweet_has_url_url_df=rels[("tweet", "has_url", "url")],
178
+ url_df=nodes["url"],
179
+ image_df=nodes["image"],
180
+ )
181
+
182
+ # Extract data relying on article, image and url data, as well has the
183
+ # (:Article)-[:HAS_TOP_IMAGE_URL]->(:Url) relation
184
+ top_image_url_rel = rels[("article", "has_top_image_url", "url")]
185
+ rels[
186
+ ("article", "has_top_image", "image")
187
+ ] = self._extract_article_has_top_image_image(
188
+ article_has_top_image_url_url_df=top_image_url_rel,
189
+ url_df=nodes["url"],
190
+ image_df=nodes["image"],
191
+ )
192
+
193
+ # Extract data relying on image and url data, as well has the
194
+ # (:User)-[:HAS_PROFILE_PICTURE_URL]->(:Url) relation
195
+ has_profile_pic_df = rels[("user", "has_profile_picture_url", "url")]
196
+ rels[
197
+ ("user", "has_profile_picture", "image")
198
+ ] = self._extract_user_has_profile_picture_image(
199
+ user_has_profile_picture_url_url_df=has_profile_pic_df,
200
+ url_df=nodes["url"],
201
+ image_df=nodes["image"],
202
+ )
203
+
204
+ return nodes, rels
205
+
206
+ def _extract_user_posted_tweet(
207
+ self, tweet_df: pd.DataFrame, user_df: pd.DataFrame
208
+ ) -> pd.DataFrame:
209
+ """Extract (:User)-[:POSTED]->(:Tweet) relation data.
210
+
211
+ Args:
212
+ tweet_df (pd.DataFrame):
213
+ A dataframe of tweets.
214
+ user_df (pd.DataFrame):
215
+ A dataframe of users.
216
+
217
+ Returns:
218
+ pd.DataFrame:
219
+ A dataframe of relations.
220
+ """
221
+ if len(tweet_df) and len(user_df):
222
+ merged = (
223
+ tweet_df[["author_id"]]
224
+ .dropna()
225
+ .reset_index()
226
+ .rename(columns=dict(index="tweet_idx"))
227
+ .astype({"author_id": np.uint64})
228
+ .merge(
229
+ user_df[["user_id"]]
230
+ .reset_index()
231
+ .rename(columns=dict(index="user_idx")),
232
+ left_on="author_id",
233
+ right_on="user_id",
234
+ )
235
+ )
236
+ data_dict = dict(
237
+ src=merged.user_idx.tolist(), tgt=merged.tweet_idx.tolist()
238
+ )
239
+ return pd.DataFrame(data_dict)
240
+ else:
241
+ return pd.DataFrame()
242
+
243
+ def _extract_user_posted_reply(
244
+ self, reply_df: pd.DataFrame, user_df: pd.DataFrame
245
+ ) -> pd.DataFrame:
246
+ """Extract (:User)-[:POSTED]->(:Reply) relation data.
247
+
248
+ Args:
249
+ reply_df (pd.DataFrame):
250
+ A dataframe of replies.
251
+ user_df (pd.DataFrame):
252
+ A dataframe of users.
253
+
254
+ Returns:
255
+ pd.DataFrame:
256
+ A dataframe of relations.
257
+ """
258
+ if self.include_replies and len(reply_df) and len(user_df):
259
+ merged = (
260
+ reply_df[["author_id"]]
261
+ .dropna()
262
+ .reset_index()
263
+ .rename(columns=dict(index="reply_idx"))
264
+ .astype({"author_id": np.uint64})
265
+ .merge(
266
+ user_df[["user_id"]]
267
+ .reset_index()
268
+ .rename(columns=dict(index="user_idx")),
269
+ left_on="author_id",
270
+ right_on="user_id",
271
+ )
272
+ )
273
+ data_dict = dict(
274
+ src=merged.user_idx.tolist(), tgt=merged.reply_idx.tolist()
275
+ )
276
+ return pd.DataFrame(data_dict)
277
+ else:
278
+ return pd.DataFrame()
279
+
280
+ def _extract_tweet_mentions_user(
281
+ self, tweet_df: pd.DataFrame, user_df: pd.DataFrame
282
+ ) -> pd.DataFrame:
283
+ """Extract (:Tweet)-[:MENTIONS]->(:User) relation data.
284
+
285
+ Args:
286
+ tweet_df (pd.DataFrame):
287
+ A dataframe of tweets.
288
+ user_df (pd.DataFrame):
289
+ A dataframe of users.
290
+
291
+ Returns:
292
+ pd.DataFrame:
293
+ A dataframe of relations.
294
+ """
295
+ mentions_exist = "entities.mentions" in tweet_df.columns
296
+ if self.include_mentions and mentions_exist and len(tweet_df) and len(user_df):
297
+
298
+ def extract_mention(dcts: List[dict]) -> List[Union[int, str]]:
299
+ """Extracts user ids from a list of dictionaries.
300
+
301
+ Args:
302
+ dcts (List[dict]):
303
+ A list of dictionaries.
304
+
305
+ Returns:
306
+ List[Union[int, str]]:
307
+ A list of user ids.
308
+ """
309
+ return [dct["id"] for dct in dcts]
310
+
311
+ merged = (
312
+ tweet_df[["entities.mentions"]]
313
+ .dropna()
314
+ .applymap(extract_mention)
315
+ .reset_index()
316
+ .rename(columns=dict(index="tweet_idx"))
317
+ .explode("entities.mentions")
318
+ .astype({"entities.mentions": np.uint64})
319
+ .merge(
320
+ user_df[["user_id"]]
321
+ .reset_index()
322
+ .rename(columns=dict(index="user_idx")),
323
+ left_on="entities.mentions",
324
+ right_on="user_id",
325
+ )
326
+ )
327
+ data_dict = dict(
328
+ src=merged.tweet_idx.tolist(), tgt=merged.user_idx.tolist()
329
+ )
330
+ return pd.DataFrame(data_dict)
331
+ else:
332
+ return pd.DataFrame()
333
+
334
+ def _extract_user_mentions_user(self, user_df: pd.DataFrame) -> pd.DataFrame:
335
+ """Extract (:User)-[:MENTIONS]->(:User) relation data.
336
+
337
+ Args:
338
+ user_df (pd.DataFrame):
339
+ A dataframe of users.
340
+
341
+ Returns:
342
+ pd.DataFrame:
343
+ A dataframe of relations.
344
+ """
345
+ user_cols = user_df.columns
346
+ mentions_exist = "entities.description.mentions" in user_cols
347
+ if self.include_mentions and mentions_exist and len(user_df):
348
+
349
+ def extract_mention(dcts: List[dict]) -> List[str]:
350
+ """Extracts user ids from a list of dictionaries.
351
+
352
+ Args:
353
+ dcts (List[dict]):
354
+ A list of dictionaries.
355
+
356
+ Returns:
357
+ List[str]:
358
+ A list of user ids.
359
+ """
360
+ return [dct["username"] for dct in dcts]
361
+
362
+ merged = (
363
+ user_df[["entities.description.mentions"]]
364
+ .dropna()
365
+ .applymap(extract_mention)
366
+ .reset_index()
367
+ .rename(columns=dict(index="user_idx1"))
368
+ .explode("entities.description.mentions")
369
+ .merge(
370
+ user_df[["username"]]
371
+ .reset_index()
372
+ .rename(columns=dict(index="user_idx2")),
373
+ left_on="entities.description.mentions",
374
+ right_on="username",
375
+ )
376
+ )
377
+ data_dict = dict(
378
+ src=merged.user_idx1.tolist(), tgt=merged.user_idx2.tolist()
379
+ )
380
+ return pd.DataFrame(data_dict)
381
+ else:
382
+ return pd.DataFrame()
383
+
384
+ def _extract_tweet_has_hashtag_hashtag(
385
+ self, tweet_df: pd.DataFrame, hashtag_df: pd.DataFrame
386
+ ) -> pd.DataFrame:
387
+ """Extract (:Tweet)-[:HAS_HASHTAG]->(:Hashtag) relation data.
388
+
389
+ Args:
390
+ tweet_df (pd.DataFrame):
391
+ A dataframe of tweets.
392
+ hashtag_df (pd.DataFrame):
393
+ A dataframe of hashtags.
394
+
395
+ Returns:
396
+ pd.DataFrame:
397
+ A dataframe of relations.
398
+ """
399
+ hashtags_exist = "entities.hashtags" in tweet_df.columns
400
+ if (
401
+ self.include_hashtags
402
+ and hashtags_exist
403
+ and len(tweet_df)
404
+ and len(hashtag_df)
405
+ ):
406
+
407
+ def extract_hashtag(dcts: List[dict]) -> List[Union[str, None]]:
408
+ """Extracts hashtags from a list of dictionaries.
409
+
410
+ Args:
411
+ dcts (list of dict):
412
+ A list of dictionaries.
413
+
414
+ Returns:
415
+ list of str or None:
416
+ A list of hashtags.
417
+ """
418
+ return [dct.get("tag") for dct in dcts]
419
+
420
+ merged = (
421
+ tweet_df[["entities.hashtags"]]
422
+ .dropna()
423
+ .applymap(extract_hashtag)
424
+ .reset_index()
425
+ .rename(columns=dict(index="tweet_idx"))
426
+ .explode("entities.hashtags")
427
+ .merge(
428
+ hashtag_df[["tag"]]
429
+ .reset_index()
430
+ .rename(columns=dict(index="tag_idx")),
431
+ left_on="entities.hashtags",
432
+ right_on="tag",
433
+ )
434
+ )
435
+ data_dict = dict(src=merged.tweet_idx.tolist(), tgt=merged.tag_idx.tolist())
436
+ return pd.DataFrame(data_dict)
437
+ else:
438
+ return pd.DataFrame()
439
+
440
+ def _extract_user_has_hashtag_hashtag(
441
+ self, user_df: pd.DataFrame, hashtag_df: pd.DataFrame
442
+ ) -> pd.DataFrame:
443
+ """Extract (:User)-[:HAS_HASHTAG]->(:Hashtag) relation data.
444
+
445
+ Args:
446
+ user_df (pd.DataFrame):
447
+ A dataframe of users.
448
+ hashtag_df (pd.DataFrame):
449
+ A dataframe of hashtags.
450
+
451
+ Returns:
452
+ pd.DataFrame: A dataframe of relations.
453
+ """
454
+ user_cols = user_df.columns
455
+ hashtags_exist = "entities.description.hashtags" in user_cols
456
+ if (
457
+ self.include_hashtags
458
+ and hashtags_exist
459
+ and len(user_df)
460
+ and len(hashtag_df)
461
+ ):
462
+
463
+ def extract_hashtag(dcts: List[dict]) -> List[Union[str, None]]:
464
+ """Extracts hashtags from a list of dictionaries.
465
+
466
+ Args:
467
+ dcts (list of dict):
468
+ A list of dictionaries.
469
+
470
+ Returns:
471
+ list of str or None:
472
+ A list of hashtags.
473
+ """
474
+ return [dct.get("tag") for dct in dcts]
475
+
476
+ merged = (
477
+ user_df[["entities.description.hashtags"]]
478
+ .dropna()
479
+ .applymap(extract_hashtag)
480
+ .reset_index()
481
+ .rename(columns=dict(index="user_idx"))
482
+ .explode("entities.description.hashtags")
483
+ .merge(
484
+ hashtag_df[["tag"]]
485
+ .reset_index()
486
+ .rename(columns=dict(index="tag_idx")),
487
+ left_on="entities.description.hashtags",
488
+ right_on="tag",
489
+ )
490
+ )
491
+ data_dict = dict(src=merged.user_idx.tolist(), tgt=merged.tag_idx.tolist())
492
+ return pd.DataFrame(data_dict)
493
+ else:
494
+ return pd.DataFrame()
495
+
496
+ def _extract_tweet_has_url_url(
497
+ self,
498
+ tweet_df: pd.DataFrame,
499
+ url_df: pd.DataFrame,
500
+ image_df: Optional[pd.DataFrame] = None,
501
+ ) -> pd.DataFrame:
502
+ """Extract (:Tweet)-[:HAS_URL]->(:Url) relation data.
503
+
504
+ Args:
505
+ tweet_df (pd.DataFrame):
506
+ A dataframe of tweets.
507
+ url_df (pd.DataFrame):
508
+ A dataframe of urls.
509
+ image_df (pd.DataFrame or None, optional):
510
+ A dataframe of images, or None if it is not available. Defaults
511
+ to None.
512
+
513
+ Returns:
514
+ pd.DataFrame:
515
+ A dataframe of relations.
516
+ """
517
+ urls_exist = (
518
+ "entities.urls" in tweet_df.columns
519
+ or "attachments.media_keys" in tweet_df.columns
520
+ )
521
+ include_images = self.include_tweet_images or self.include_extra_images
522
+ if (
523
+ (self.include_articles or include_images)
524
+ and urls_exist
525
+ and len(tweet_df)
526
+ and len(url_df)
527
+ ):
528
+
529
+ # Add the urls from the tweets themselves
530
+ def extract_url(dcts: List[dict]) -> List[Union[str, None]]:
531
+ """Extracts urls from a list of dictionaries.
532
+
533
+ Args:
534
+ dcts (List[dict]):
535
+ A list of dictionaries.
536
+
537
+ Returns:
538
+ List[str]:
539
+ A list of urls.
540
+ """
541
+ return [dct.get("expanded_url") or dct.get("url") for dct in dcts]
542
+
543
+ merged = (
544
+ tweet_df[["entities.urls"]]
545
+ .dropna()
546
+ .applymap(extract_url)
547
+ .reset_index()
548
+ .rename(columns=dict(index="tweet_idx"))
549
+ .explode("entities.urls")
550
+ .merge(
551
+ url_df[["url"]].reset_index().rename(columns=dict(index="ul_idx")),
552
+ left_on="entities.urls",
553
+ right_on="url",
554
+ )
555
+ )
556
+ data_dict = dict(src=merged.tweet_idx.tolist(), tgt=merged.ul_idx.tolist())
557
+ rel_df = pd.DataFrame(data_dict)
558
+
559
+ # Append the urls from the images
560
+ if image_df is not None and len(image_df) and include_images:
561
+ merged = (
562
+ tweet_df.reset_index()
563
+ .rename(columns=dict(index="tweet_idx"))
564
+ .explode("attachments.media_keys")
565
+ .merge(
566
+ image_df[["media_key", "url"]],
567
+ left_on="attachments.media_keys",
568
+ right_on="media_key",
569
+ )
570
+ .merge(
571
+ url_df[["url"]]
572
+ .reset_index()
573
+ .rename(columns=dict(index="ul_idx")),
574
+ on="url",
575
+ )
576
+ )
577
+ data_dict = dict(
578
+ src=merged.tweet_idx.tolist(), tgt=merged.ul_idx.tolist()
579
+ )
580
+ rel_df = pd.concat((rel_df, pd.DataFrame(data_dict))).drop_duplicates()
581
+
582
+ return rel_df
583
+
584
+ def _extract_user_has_url_url(
585
+ self, user_df: pd.DataFrame, url_df: pd.DataFrame
586
+ ) -> pd.DataFrame:
587
+ """Extract (:User)-[:HAS_URL]->(:Url) relation data.
588
+
589
+ Args:
590
+ user_df (pd.DataFrame):
591
+ A dataframe of users.
592
+ url_df (pd.DataFrame):
593
+ A dataframe of urls.
594
+
595
+ Returns:
596
+ pd.DataFrame:
597
+ A dataframe of relations.
598
+ """
599
+ user_cols = user_df.columns
600
+ url_urls_exist = "entities.url.urls" in user_cols
601
+ desc_urls_exist = "entities.description.urls" in user_cols
602
+ if url_urls_exist or desc_urls_exist and len(user_df) and len(url_df):
603
+
604
+ def extract_url(dcts: List[dict]) -> List[Union[str, None]]:
605
+ """Extracts urls from a list of dictionaries.
606
+
607
+ Args:
608
+ dcts (list of dict):
609
+ A list of dictionaries.
610
+
611
+ Returns:
612
+ list of str or None:
613
+ A list of urls.
614
+ """
615
+
616
+ return [dct.get("expanded_url") or dct.get("url") for dct in dcts]
617
+
618
+ # Initialise empty relation, which will be populated below
619
+ rel_df = pd.DataFrame()
620
+
621
+ if url_urls_exist:
622
+ merged = (
623
+ user_df[["entities.url.urls"]]
624
+ .dropna()
625
+ .applymap(extract_url)
626
+ .reset_index()
627
+ .rename(columns=dict(index="user_idx"))
628
+ .explode("entities.url.urls")
629
+ .merge(
630
+ url_df[["url"]]
631
+ .reset_index()
632
+ .rename(columns=dict(index="ul_idx")),
633
+ left_on="entities.url.urls",
634
+ right_on="url",
635
+ )
636
+ )
637
+ data_dict = dict(
638
+ src=merged.user_idx.tolist(), tgt=merged.ul_idx.tolist()
639
+ )
640
+ rel_df = (
641
+ pd.concat((rel_df, pd.DataFrame(data_dict)), axis=0)
642
+ .drop_duplicates()
643
+ .reset_index(drop=True)
644
+ )
645
+
646
+ if desc_urls_exist:
647
+ merged = (
648
+ user_df[["entities.description.urls"]]
649
+ .dropna()
650
+ .applymap(extract_url)
651
+ .reset_index()
652
+ .rename(columns=dict(index="user_idx"))
653
+ .explode("entities.description.urls")
654
+ .merge(
655
+ url_df[["url"]]
656
+ .reset_index()
657
+ .rename(columns=dict(index="ul_idx")),
658
+ left_on="entities.description.urls",
659
+ right_on="url",
660
+ )
661
+ )
662
+ data_dict = dict(
663
+ src=merged.user_idx.tolist(), tgt=merged.ul_idx.tolist()
664
+ )
665
+ rel_df = (
666
+ pd.concat((rel_df, pd.DataFrame(data_dict)), axis=0)
667
+ .drop_duplicates()
668
+ .reset_index(drop=True)
669
+ )
670
+
671
+ return rel_df
672
+ else:
673
+ return pd.DataFrame()
674
+
675
+ def _extract_user_has_profile_picture_url_url(
676
+ self, user_df: pd.DataFrame, url_df: pd.DataFrame
677
+ ) -> pd.DataFrame:
678
+ """Extract (:User)-[:HAS_PROFILE_PICTURE]->(:Url) relation data.
679
+
680
+ Args:
681
+ user_df (pd.DataFrame):
682
+ A dataframe of users.
683
+ url_df (pd.DataFrame):
684
+ A dataframe of urls.
685
+
686
+ Returns:
687
+ pd.DataFrame:
688
+ A dataframe of relations.
689
+ """
690
+ user_cols = user_df.columns
691
+ profile_images_exist = "profile_image_url" in user_cols
692
+ if (
693
+ self.include_extra_images
694
+ and profile_images_exist
695
+ and len(user_df)
696
+ and len(url_df)
697
+ ):
698
+ merged = (
699
+ user_df[["profile_image_url"]]
700
+ .dropna()
701
+ .reset_index()
702
+ .rename(columns=dict(index="user_idx"))
703
+ .merge(
704
+ url_df[["url"]].reset_index().rename(columns=dict(index="ul_idx")),
705
+ left_on="profile_image_url",
706
+ right_on="url",
707
+ )
708
+ )
709
+ data_dict = dict(src=merged.user_idx.tolist(), tgt=merged.ul_idx.tolist())
710
+ return pd.DataFrame(data_dict)
711
+ else:
712
+ return pd.DataFrame()
713
+
714
+ def _extract_articles(self, url_df: pd.DataFrame) -> pd.DataFrame:
715
+ """Extract (:Article) nodes.
716
+
717
+ Args:
718
+ url_df (pd.DataFrame):
719
+ A dataframe of urls.
720
+
721
+ Returns:
722
+ pd.DataFrame:
723
+ A dataframe of articles.
724
+ """
725
+ if self.include_articles and len(url_df):
726
+ # Create regex that filters out non-articles. These are common
727
+ # images, videos and social media websites
728
+ non_article_regexs = [
729
+ "youtu[.]*be",
730
+ "vimeo",
731
+ "spotify",
732
+ "twitter",
733
+ "instagram",
734
+ "tiktok",
735
+ "gab[.]com",
736
+ "https://t[.]me",
737
+ "imgur",
738
+ "/photo/",
739
+ "mp4",
740
+ "mov",
741
+ "jpg",
742
+ "jpeg",
743
+ "bmp",
744
+ "png",
745
+ "gif",
746
+ "pdf",
747
+ ]
748
+ non_article_regex = "(" + "|".join(non_article_regexs) + ")"
749
+
750
+ # Filter out the URLs to get the potential article URLs
751
+ article_urls = [
752
+ url
753
+ for url in url_df.url.tolist()
754
+ if re.search(non_article_regex, url) is None
755
+ ]
756
+
757
+ # Loop over all the Url nodes
758
+ data_dict = defaultdict(list)
759
+ with mp.Pool(processes=self.n_jobs) as pool:
760
+ for result in tqdm(
761
+ pool.imap_unordered(
762
+ process_article_url, article_urls, chunksize=self.chunksize
763
+ ),
764
+ desc="Parsing articles",
765
+ total=len(article_urls),
766
+ ):
767
+
768
+ # Skip result if URL is not parseable
769
+ if result is None:
770
+ continue
771
+
772
+ # Store the data in the data dictionary
773
+ data_dict["url"].append(result["url"])
774
+ data_dict["title"].append(result["title"])
775
+ data_dict["content"].append(result["content"])
776
+ data_dict["authors"].append(result["authors"])
777
+ data_dict["publish_date"].append(result["publish_date"])
778
+ data_dict["top_image_url"].append(result["top_image_url"])
779
+
780
+ # Convert the data dictionary to a dataframe and return it
781
+ return pd.DataFrame(data_dict)
782
+ else:
783
+ return pd.DataFrame()
784
+
785
+ def _extract_article_has_top_image_url_url(
786
+ self, article_df: pd.DataFrame, url_df: pd.DataFrame
787
+ ) -> pd.DataFrame:
788
+ """Extract (:Article)-[:HAS_TOP_IMAGE_URL]->(:Url) relation data.
789
+
790
+ Args:
791
+ article_df (pd.DataFrame):
792
+ A dataframe of articles.
793
+ url_df (pd.DataFrame):
794
+ A dataframe of urls.
795
+
796
+ Returns:
797
+ pd.DataFrame:
798
+ A dataframe of relations.
799
+ """
800
+ if (
801
+ self.include_articles
802
+ and self.include_extra_images
803
+ and len(article_df)
804
+ and len(url_df)
805
+ ):
806
+
807
+ # Create relation
808
+ merged = (
809
+ article_df[["top_image_url"]]
810
+ .dropna()
811
+ .reset_index()
812
+ .rename(columns=dict(index="art_idx"))
813
+ .merge(
814
+ url_df[["url"]].reset_index().rename(columns=dict(index="ul_idx")),
815
+ left_on="top_image_url",
816
+ right_on="url",
817
+ )
818
+ )
819
+ data_dict = dict(src=merged.art_idx.tolist(), tgt=merged.ul_idx.tolist())
820
+ return pd.DataFrame(data_dict)
821
+ else:
822
+ return pd.DataFrame()
823
+
824
+ def _extract_tweet_has_article_article(
825
+ self,
826
+ tweet_has_url_url_df: pd.DataFrame,
827
+ article_df: pd.DataFrame,
828
+ url_df: pd.DataFrame,
829
+ ) -> pd.DataFrame:
830
+ """Extract (:Tweet)-[:HAS_ARTICLE]->(:Article) relation data.
831
+
832
+ Args:
833
+ tweet_has_url_url_df (pd.DataFrame):
834
+ A dataframe of relations.
835
+ article_df (pd.DataFrame):
836
+ A dataframe of articles.
837
+ url_df (pd.DataFrame):
838
+ A dataframe of urls.
839
+
840
+ Returns:
841
+ pd.DataFrame:
842
+ A dataframe of relations.
843
+ """
844
+ if (
845
+ self.include_articles
846
+ and len(tweet_has_url_url_df)
847
+ and len(article_df)
848
+ and len(url_df)
849
+ ):
850
+ merged = (
851
+ tweet_has_url_url_df.rename(columns=dict(src="tweet_idx", tgt="ul_idx"))
852
+ .merge(
853
+ url_df[["url"]].reset_index().rename(columns=dict(index="ul_idx")),
854
+ on="ul_idx",
855
+ )
856
+ .merge(
857
+ article_df[["url"]]
858
+ .reset_index()
859
+ .rename(columns=dict(index="art_idx")),
860
+ on="url",
861
+ )
862
+ )
863
+ data_dict = dict(src=merged.tweet_idx.tolist(), tgt=merged.art_idx.tolist())
864
+ return pd.DataFrame(data_dict)
865
+ else:
866
+ return pd.DataFrame()
867
+
868
+ def _extract_images(
869
+ self, url_df: pd.DataFrame, article_df: pd.DataFrame
870
+ ) -> pd.DataFrame:
871
+ """Extract (:Image) nodes.
872
+
873
+ Args:
874
+ url_df (pd.DataFrame):
875
+ A dataframe of urls.
876
+ article_df (pd.DataFrame):
877
+ A dataframe of articles.
878
+
879
+ Returns:
880
+ pd.DataFrame:
881
+ A dataframe of images.
882
+ """
883
+ if self.include_tweet_images or self.include_extra_images and len(url_df):
884
+
885
+ # If there are no articles then set `article_df` to have an empty `url`
886
+ # column
887
+ if not len(article_df):
888
+ article_df = pd.DataFrame(columns=["url"])
889
+
890
+ # Start with all the URLs that have not already been parsed as articles
891
+ image_urls = [
892
+ url for url in url_df.url.tolist() if url not in article_df.url.tolist()
893
+ ]
894
+
895
+ # Filter the resulting list of URLs using a hardcoded list of image formats
896
+ regex = "|".join(
897
+ [
898
+ "png",
899
+ "jpg",
900
+ "jpeg",
901
+ "bmp",
902
+ "pdf",
903
+ "jfif",
904
+ "tiff",
905
+ "ppm",
906
+ "pgm",
907
+ "pbm",
908
+ "pnm",
909
+ "webp",
910
+ "hdr",
911
+ "heif",
912
+ ]
913
+ )
914
+ image_urls = [
915
+ url for url in image_urls if re.search(regex, url) is not None
916
+ ]
917
+
918
+ # Loop over all the Url nodes
919
+ data_dict = defaultdict(list)
920
+ with mp.Pool(processes=self.n_jobs) as pool:
921
+ for result in tqdm(
922
+ pool.imap_unordered(
923
+ process_image_url, image_urls, chunksize=self.chunksize
924
+ ),
925
+ desc="Parsing images",
926
+ total=len(image_urls),
927
+ ):
928
+
929
+ # Store the data in the data dictionary if it was parseable
930
+ if (
931
+ result is not None
932
+ and len(result["pixels"].shape) == 3
933
+ and result["pixels"].shape[2] == 3
934
+ ):
935
+ data_dict["url"].append(result["url"])
936
+ data_dict["pixels"].append(result["pixels"])
937
+ data_dict["height"].append(result["height"])
938
+ data_dict["width"].append(result["width"])
939
+
940
+ # Convert the data dictionary to a dataframe and store it as the `Image`
941
+ # node.
942
+ return pd.DataFrame(data_dict)
943
+ else:
944
+ return pd.DataFrame()
945
+
946
+ def _extract_tweet_has_image_image(
947
+ self,
948
+ tweet_has_url_url_df: pd.DataFrame,
949
+ url_df: pd.DataFrame,
950
+ image_df: pd.DataFrame,
951
+ ) -> pd.DataFrame:
952
+ """Extract (:Tweet)-[:HAS_IMAGE]->(:Image) relation data.
953
+
954
+ Args:
955
+ tweet_has_url_url_df (pd.DataFrame):
956
+ A dataframe of relations.
957
+ url_df (pd.DataFrame):
958
+ A dataframe of urls.
959
+ image_df (pd.DataFrame):
960
+ A dataframe of images.
961
+
962
+ Returns:
963
+ pd.DataFrame:
964
+ A dataframe of relations.
965
+ """
966
+ if (
967
+ len(tweet_has_url_url_df)
968
+ and len(url_df)
969
+ and len(image_df)
970
+ and self.include_tweet_images
971
+ ):
972
+ url_idx = dict(index="ul_idx")
973
+ img_idx = dict(index="im_idx")
974
+ if len(tweet_has_url_url_df):
975
+ merged = (
976
+ tweet_has_url_url_df.rename(
977
+ columns=dict(src="tweet_idx", tgt="ul_idx")
978
+ )
979
+ .merge(
980
+ url_df[["url"]].reset_index().rename(columns=url_idx),
981
+ on="ul_idx",
982
+ )
983
+ .merge(
984
+ image_df[["url"]].reset_index().rename(columns=img_idx),
985
+ on="url",
986
+ )
987
+ )
988
+ data_dict = dict(
989
+ src=merged.tweet_idx.tolist(), tgt=merged.im_idx.tolist()
990
+ )
991
+ return pd.DataFrame(data_dict)
992
+ else:
993
+ return pd.DataFrame()
994
+
995
+ def _extract_article_has_top_image_image(
996
+ self,
997
+ article_has_top_image_url_url_df: pd.DataFrame,
998
+ url_df: pd.DataFrame,
999
+ image_df: pd.DataFrame,
1000
+ ) -> pd.DataFrame:
1001
+ """Extract (:Article)-[:HAS_TOP_IMAGE]->(:Image) relation data.
1002
+
1003
+ Args:
1004
+ article_has_top_image_url_url_df (pd.DataFrame):
1005
+ A dataframe of relations.
1006
+ url_df (pd.DataFrame):
1007
+ A dataframe of urls.
1008
+ image_df (pd.DataFrame):
1009
+ A dataframe of images.
1010
+
1011
+ Returns:
1012
+ pd.DataFrame: A dataframe of relations.
1013
+ """
1014
+ if (
1015
+ self.include_articles
1016
+ and self.include_extra_images
1017
+ and len(article_has_top_image_url_url_df)
1018
+ and len(url_df)
1019
+ and len(image_df)
1020
+ ):
1021
+ url_idx = dict(index="ul_idx")
1022
+ img_idx = dict(index="im_idx")
1023
+ if self.include_articles:
1024
+ merged = (
1025
+ article_has_top_image_url_url_df.rename(
1026
+ columns=dict(src="art_idx", tgt="ul_idx")
1027
+ )
1028
+ .merge(
1029
+ url_df[["url"]].reset_index().rename(columns=url_idx),
1030
+ on="ul_idx",
1031
+ )
1032
+ .merge(
1033
+ image_df[["url"]].reset_index().rename(columns=img_idx),
1034
+ on="url",
1035
+ )
1036
+ )
1037
+ data_dict = dict(
1038
+ src=merged.art_idx.tolist(), tgt=merged.im_idx.tolist()
1039
+ )
1040
+ return pd.DataFrame(data_dict)
1041
+ else:
1042
+ return pd.DataFrame()
1043
+
1044
+ def _extract_user_has_profile_picture_image(
1045
+ self,
1046
+ user_has_profile_picture_url_url_df: pd.DataFrame,
1047
+ url_df: pd.DataFrame,
1048
+ image_df: pd.DataFrame,
1049
+ ) -> pd.DataFrame:
1050
+ """Extract (:User)-[:HAS_PROFILE_PICTURE]->(:Image) relation data.
1051
+
1052
+ Args:
1053
+ user_has_profile_picture_url_url_df (pd.DataFrame):
1054
+ A dataframe of relations.
1055
+ url_df (pd.DataFrame):
1056
+ A dataframe of urls.
1057
+ image_df (pd.DataFrame):
1058
+ A dataframe of images.
1059
+
1060
+ Returns:
1061
+ pd.DataFrame: A dataframe of relations.
1062
+ """
1063
+ if (
1064
+ self.include_extra_images
1065
+ and len(image_df)
1066
+ and len(url_df)
1067
+ and len(user_has_profile_picture_url_url_df)
1068
+ ):
1069
+ merged = (
1070
+ user_has_profile_picture_url_url_df.rename(
1071
+ columns=dict(src="user_idx", tgt="ul_idx")
1072
+ )
1073
+ .merge(
1074
+ url_df[["url"]].reset_index().rename(columns=dict(index="ul_idx")),
1075
+ on="ul_idx",
1076
+ )
1077
+ .merge(
1078
+ image_df[["url"]]
1079
+ .reset_index()
1080
+ .rename(columns=dict(index="im_idx")),
1081
+ on="url",
1082
+ )
1083
+ )
1084
+ data_dict = dict(src=merged.user_idx.tolist(), tgt=merged.im_idx.tolist())
1085
+ return pd.DataFrame(data_dict)
1086
+ else:
1087
+ return pd.DataFrame()
1088
+
1089
+ def _extract_hashtags(
1090
+ self, tweet_df: pd.DataFrame, user_df: pd.DataFrame
1091
+ ) -> pd.DataFrame:
1092
+ """Extract (:Hashtag) node data.
1093
+
1094
+ Args:
1095
+ tweet_df (pd.DataFrame):
1096
+ A dataframe of tweets.
1097
+ user_df (pd.DataFrame):
1098
+ A dataframe of users.
1099
+
1100
+ Returns:
1101
+ pd.DataFrame:
1102
+ A dataframe of hashtags.
1103
+ """
1104
+ if self.include_hashtags and len(tweet_df) and len(user_df):
1105
+
1106
+ # Initialise the hashtag dataframe
1107
+ hashtag_df = pd.DataFrame()
1108
+
1109
+ def extract_hashtag(dcts: List[dict]) -> List[Union[str, None]]:
1110
+ """Extracts hashtags from a list of dictionaries.
1111
+
1112
+ Args:
1113
+ dcts (list of dict):
1114
+ A list of dictionaries.
1115
+
1116
+ Returns:
1117
+ list of str or None:
1118
+ A list of hashtags.
1119
+ """
1120
+ return [dct.get("tag") for dct in dcts]
1121
+
1122
+ # Add hashtags from tweets
1123
+ if "entities.hashtags" in tweet_df.columns:
1124
+ hashtags = (
1125
+ tweet_df["entities.hashtags"]
1126
+ .dropna()
1127
+ .map(extract_hashtag)
1128
+ .explode()
1129
+ .tolist()
1130
+ )
1131
+ hashtag_dict = pd.DataFrame(dict(tag=hashtags))
1132
+ hashtag_df = (
1133
+ pd.concat((hashtag_df, pd.DataFrame(hashtag_dict)), axis=0)
1134
+ .drop_duplicates()
1135
+ .reset_index(drop=True)
1136
+ )
1137
+
1138
+ # Add hashtags from users
1139
+ if "entities.description.hashtags" in user_df.columns:
1140
+ hashtags = (
1141
+ user_df["entities.description.hashtags"]
1142
+ .dropna()
1143
+ .map(extract_hashtag)
1144
+ .explode()
1145
+ .tolist()
1146
+ )
1147
+ hashtag_dict = pd.DataFrame(dict(tag=hashtags))
1148
+ hashtag_df = (
1149
+ pd.concat((hashtag_df, pd.DataFrame(hashtag_dict)), axis=0)
1150
+ .drop_duplicates()
1151
+ .reset_index(drop=True)
1152
+ )
1153
+
1154
+ return hashtag_df
1155
+ else:
1156
+ return pd.DataFrame()
1157
+
1158
+ def _extract_urls(
1159
+ self,
1160
+ tweet_dicusses_claim_df: pd.DataFrame,
1161
+ user_posted_tweet_df: pd.DataFrame,
1162
+ user_df: pd.DataFrame,
1163
+ tweet_df: pd.DataFrame,
1164
+ article_df: Optional[pd.DataFrame] = None,
1165
+ image_df: Optional[pd.DataFrame] = None,
1166
+ ) -> pd.DataFrame:
1167
+ """Extract (:Url) node data.
1168
+
1169
+ Note that this does not extract the top image urls from the articles.
1170
+ This will be added with the _update_urls_from_articles method, after
1171
+ the articles have been extracted.
1172
+
1173
+ Args:
1174
+ tweet_dicusses_claim_df (pd.DataFrame):
1175
+ A dataframe of tweet_dicusses_claim nodes.
1176
+ user_posted_tweet_df (pd.DataFrame):
1177
+ A dataframe of user_posted_tweet nodes.
1178
+ user_df (pd.DataFrame):
1179
+ A dataframe of user nodes.
1180
+ tweet_df (pd.DataFrame):
1181
+ A dataframe of tweet nodes.
1182
+ article_df (pd.DataFrame or None, optional):
1183
+ A dataframe of article nodes, of None if no articles are
1184
+ available. Defaults to None.
1185
+ image_df (pd.DataFrame, or None, optional):
1186
+ A dataframe of image nodes, or None if no images are available.
1187
+ Defaults to None.
1188
+
1189
+ Returns:
1190
+ pd.DataFrame: A dataframe of url nodes.
1191
+ """
1192
+ if (
1193
+ len(tweet_dicusses_claim_df) == 0
1194
+ or len(user_df) == 0
1195
+ or len(tweet_df) == 0
1196
+ or len(user_posted_tweet_df) == 0
1197
+ ):
1198
+ return pd.DataFrame()
1199
+
1200
+ # Define dataframe with the source tweets
1201
+ is_src = tweet_df.index.isin(tweet_dicusses_claim_df.src.tolist())
1202
+ src_tweets = tweet_df[is_src]
1203
+
1204
+ # Define dataframe with the source users
1205
+ posted_rel = user_posted_tweet_df
1206
+ is_src = posted_rel[posted_rel.tgt.isin(src_tweets.index.tolist())].src.tolist()
1207
+ src_users = user_df.loc[is_src]
1208
+
1209
+ # Initialise empty URL dataframe
1210
+ url_df = pd.DataFrame()
1211
+
1212
+ # Add urls from source tweets
1213
+ if "entities.urls" in tweet_df.columns:
1214
+
1215
+ def extract_url(dcts: List[dict]) -> List[Union[str, None]]:
1216
+ """Extracts urls from a list of dictionaries.
1217
+
1218
+ Args:
1219
+ dcts (List[dict]):
1220
+ A list of dictionaries.
1221
+
1222
+ Returns:
1223
+ List[Union[str, None]]:
1224
+ A list of urls.
1225
+ """
1226
+ return [dct.get("expanded_url") or dct.get("url") for dct in dcts]
1227
+
1228
+ urls = (
1229
+ src_tweets["entities.urls"].dropna().map(extract_url).explode().tolist()
1230
+ )
1231
+ url_dict = pd.DataFrame(dict(url=urls))
1232
+ url_df = (
1233
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1234
+ .drop_duplicates()
1235
+ .reset_index(drop=True)
1236
+ )
1237
+
1238
+ # Add urls from source user urls
1239
+ if "entities.url.urls" in user_df.columns:
1240
+
1241
+ def extract_url(dcts: List[dict]) -> List[Union[str, None]]:
1242
+ """Extracts urls from a list of dictionaries.
1243
+
1244
+ Args:
1245
+ dcts (List[dict]):
1246
+ A list of dictionaries.
1247
+
1248
+ Returns:
1249
+ List[Union[str, None]]:
1250
+ A list of urls.
1251
+ """
1252
+ return [dct.get("expanded_url") or dct.get("url") for dct in dcts]
1253
+
1254
+ urls = (
1255
+ src_users["entities.url.urls"]
1256
+ .dropna()
1257
+ .map(extract_url)
1258
+ .explode()
1259
+ .tolist()
1260
+ )
1261
+ url_dict = pd.DataFrame(dict(url=urls))
1262
+ url_df = (
1263
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1264
+ .drop_duplicates()
1265
+ .reset_index(drop=True)
1266
+ )
1267
+
1268
+ # Add urls from source user descriptions
1269
+ if "entities.description.urls" in user_df.columns:
1270
+
1271
+ def extract_url(dcts: List[dict]) -> List[Union[str, None]]:
1272
+ """Extracts urls from a list of dictionaries.
1273
+
1274
+ Args:
1275
+ dcts (List[dict]):
1276
+ A list of dictionaries.
1277
+
1278
+ Returns:
1279
+ List[Union[str, None]]:
1280
+ A list of urls.
1281
+ """
1282
+ return [dct.get("expanded_url") or dct.get("url") for dct in dcts]
1283
+
1284
+ urls = (
1285
+ src_users["entities.description.urls"]
1286
+ .dropna()
1287
+ .map(extract_url)
1288
+ .explode()
1289
+ .tolist()
1290
+ )
1291
+ url_dict = pd.DataFrame(dict(url=urls))
1292
+ url_df = (
1293
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1294
+ .drop_duplicates()
1295
+ .reset_index(drop=True)
1296
+ )
1297
+
1298
+ # Add urls from images
1299
+ if (
1300
+ image_df is not None
1301
+ and len(image_df)
1302
+ and self.include_tweet_images
1303
+ and "attachments.media_keys" in tweet_df.columns
1304
+ ):
1305
+ urls = (
1306
+ src_tweets[["attachments.media_keys"]]
1307
+ .dropna()
1308
+ .explode("attachments.media_keys")
1309
+ .merge(
1310
+ image_df[["media_key", "url"]],
1311
+ left_on="attachments.media_keys",
1312
+ right_on="media_key",
1313
+ )
1314
+ .url.tolist()
1315
+ )
1316
+ url_dict = pd.DataFrame(dict(url=urls))
1317
+ url_df = (
1318
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1319
+ .drop_duplicates()
1320
+ .reset_index(drop=True)
1321
+ )
1322
+
1323
+ # Add urls from profile pictures
1324
+ if self.include_extra_images and "profile_image_url" in user_df.columns:
1325
+
1326
+ def extract_url(dcts: List[dict]) -> List[Union[str, None]]:
1327
+ """Extracts urls from a list of dictionaries.
1328
+
1329
+ Args:
1330
+ dcts (List[dict]):
1331
+ A list of dictionaries.
1332
+
1333
+ Returns:
1334
+ List[Union[str, None]]:
1335
+ A list of urls.
1336
+ """
1337
+ return [dct.get("expanded_url") or dct.get("url") for dct in dcts]
1338
+
1339
+ urls = src_users["profile_image_url"].dropna().tolist()
1340
+ url_dict = pd.DataFrame(dict(url=urls))
1341
+ url_df = (
1342
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1343
+ .drop_duplicates()
1344
+ .reset_index(drop=True)
1345
+ )
1346
+
1347
+ # Add urls from articles
1348
+ if article_df is not None and len(article_df) and self.include_articles:
1349
+ urls = article_df.url.dropna().tolist()
1350
+ url_dict = pd.DataFrame(dict(url=urls))
1351
+ url_df = (
1352
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1353
+ .drop_duplicates()
1354
+ .reset_index(drop=True)
1355
+ )
1356
+
1357
+ return url_df
1358
+
1359
+ def _update_urls_from_articles(
1360
+ self, url_df: pd.DataFrame, article_df: pd.DataFrame
1361
+ ) -> pd.DataFrame:
1362
+ """Updates the url_df with the urls from the articles.
1363
+
1364
+ Args:
1365
+ url_df (pd.DataFrame):
1366
+ A dataframe with the urls.
1367
+ article_df (pd.DataFrame):
1368
+ A dataframe with the articles.
1369
+
1370
+ Returns:
1371
+ pd.DataFrame:
1372
+ A dataframe with the urls.
1373
+ """
1374
+ if self.include_extra_images and len(article_df) and len(url_df):
1375
+ urls = article_df.top_image_url.dropna().tolist()
1376
+ url_dict = pd.DataFrame(dict(url=urls))
1377
+ url_df = (
1378
+ pd.concat((url_df, pd.DataFrame(url_dict)), axis=0)
1379
+ .drop_duplicates()
1380
+ .reset_index(drop=True)
1381
+ )
1382
+ return url_df
src/mumin/dataset.py ADDED
@@ -0,0 +1,1152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Script containing the main dataset class"""
2
+
3
+ import io
4
+ import logging
5
+ import multiprocessing as mp
6
+ import os
7
+ import warnings
8
+ import zipfile
9
+ from functools import partial
10
+ from pathlib import Path
11
+ from shutil import rmtree
12
+ from typing import Dict, List, Optional, Tuple, Union
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ import requests
17
+ from dotenv import load_dotenv
18
+ from tqdm.auto import tqdm
19
+
20
+ from .data_extractor import DataExtractor
21
+ from .dgl import build_dgl_dataset
22
+ from .embedder import Embedder
23
+ from .id_updator import IdUpdator
24
+ from .twitter import Twitter
25
+
26
+ # Load environment variables
27
+ load_dotenv()
28
+
29
+
30
+ # Set up logging
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ # Disable tokenizer parallelism
35
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
36
+
37
+
38
+ # Prevents crashes during data extraction on MacOS
39
+ os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
40
+
41
+
42
+ # Allows progress bars with `pd.DataFrame.progress_apply`
43
+ tqdm.pandas()
44
+
45
+
46
+ class MuminDataset:
47
+ """The MuMiN misinformation dataset, from [1].
48
+
49
+ Args:
50
+ twitter_bearer_token (str or None, optional):
51
+ The Twitter bearer token. If None then the the bearer token must be stored
52
+ in the environment variable `TWITTER_API_KEY`, or placed in a file named
53
+ `.env` in the working directory, formatted as "TWITTER_API_KEY=xxxxx".
54
+ Defaults to None.
55
+ size (str, optional):
56
+ The size of the dataset. Can be either 'small', 'medium' or 'large'.
57
+ Defaults to 'small'.
58
+ include_replies (bool, optional):
59
+ Whether to include replies and quote tweets in the dataset. Defaults to
60
+ True.
61
+ include_articles (bool, optional):
62
+ Whether to include articles in the dataset. This will mean that compilation
63
+ of the dataset will take a bit longer, as these need to be downloaded and
64
+ parsed. Defaults to True.
65
+ include_tweet_images (bool, optional):
66
+ Whether to include images from the tweets in the dataset. This will mean
67
+ that compilation of the dataset will take a bit longer, as these need to be
68
+ downloaded and parsed. Defaults to True.
69
+ include_extra_images (bool, optional):
70
+ Whether to include images from the articles and users in the dataset. This
71
+ will mean that compilation of the dataset will take a bit longer, as these
72
+ need to be downloaded and parsed. Defaults to False.
73
+ include_hashtags (bool, optional):
74
+ Whether to include hashtags in the dataset. Defaults to True.
75
+ include_mentions (bool, optional):
76
+ Whether to include mentions in the dataset. Defaults to True.
77
+ include_timelines (bool, optional):
78
+ Whether to include timelines in the dataset. Defaults to False.
79
+ text_embedding_model_id (str, optional):
80
+ The HuggingFace Hub model ID to use when embedding texts. Defaults to
81
+ 'xlm-roberta-base'.
82
+ image_embedding_model_id (str, optional):
83
+ The HuggingFace Hub model ID to use when embedding images. Defaults to
84
+ 'google/vit-base-patch16-224-in21k'.
85
+ dataset_path (str, pathlib Path or None, optional):
86
+ The path to the file where the dataset should be stored. If None then the
87
+ dataset will be stored at './mumin-<size>.zip'. Defaults to None.
88
+ n_jobs (int, optional):
89
+ The number of jobs to use for parallel processing. Defaults to the number
90
+ of available CPU cores minus one.
91
+ chunksize (int, optional):
92
+ The number of articles/images to process in each job. This speeds up
93
+ processing time, but also increases memory load. Defaults to 10.
94
+ verbose (bool, optional):
95
+ Whether extra information should be outputted. Defaults to True.
96
+
97
+ Attributes:
98
+ include_replies (bool): Whether to include replies.
99
+ include_articles (bool): Whether to include articles.
100
+ include_tweet_images (bool): Whether to include tweet images.
101
+ include_extra_images (bool): Whether to include user/article images.
102
+ include_hashtags (bool): Whether to include hashtags.
103
+ include_mentions (bool): Whether to include mentions.
104
+ include_timelines (bool): Whether to include timelines.
105
+ size (str): The size of the dataset.
106
+ dataset_path (pathlib Path): The dataset file.
107
+ text_embedding_model_id (str): The model ID used for embedding text.
108
+ image_embedding_model_id (str): The model ID used for embedding images.
109
+ nodes (dict): The nodes of the dataset.
110
+ rels (dict): The relations of the dataset.
111
+ rehydrated (bool): Whether the tweets and/or replies have been rehydrated.
112
+ compiled (bool): Whether the dataset has been compiled.
113
+ n_jobs (int): The number of jobs to use for parallel processing.
114
+ chunksize (int): The number of articles/images to process in each job.
115
+ verbose (bool): Whether extra information should be outputted.
116
+ download_url (str): The URL to download the dataset from.
117
+
118
+ Raises:
119
+ ValueError:
120
+ If `twitter_bearer_token` is None and the environment variable
121
+ `TWITTER_API_KEY` is not set.
122
+
123
+ References:
124
+ - [1] Nielsen and McConville: MuMiN: A Large-Scale Multilingual Multimodal
125
+ Fact-Checked Misinformation Dataset with Linked Social Network Posts
126
+ (2021)
127
+ """
128
+
129
+ download_url: str = (
130
+ "https://data.bris.ac.uk/datasets/23yv276we2mll25f"
131
+ "jakkfim2ml/23yv276we2mll25fjakkfim2ml.zip"
132
+ )
133
+ _node_dump: List[str] = [
134
+ "claim",
135
+ "tweet",
136
+ "user",
137
+ "image",
138
+ "article",
139
+ "hashtag",
140
+ "reply",
141
+ ]
142
+ _rel_dump: List[Tuple[str, str, str]] = [
143
+ ("tweet", "discusses", "claim"),
144
+ ("tweet", "mentions", "user"),
145
+ ("tweet", "has_image", "image"),
146
+ ("tweet", "has_hashtag", "hashtag"),
147
+ ("tweet", "has_article", "article"),
148
+ ("reply", "reply_to", "tweet"),
149
+ ("reply", "quote_of", "tweet"),
150
+ ("user", "posted", "tweet"),
151
+ ("user", "posted", "reply"),
152
+ ("user", "mentions", "user"),
153
+ ("user", "has_hashtag", "hashtag"),
154
+ ("user", "has_profile_picture", "image"),
155
+ ("user", "retweeted", "tweet"),
156
+ ("user", "follows", "user"),
157
+ ("article", "has_top_image", "image"),
158
+ ]
159
+
160
+ def __init__(
161
+ self,
162
+ twitter_bearer_token: Optional[str] = None,
163
+ size: str = "small",
164
+ include_replies: bool = True,
165
+ include_articles: bool = True,
166
+ include_tweet_images: bool = True,
167
+ include_extra_images: bool = False,
168
+ include_hashtags: bool = True,
169
+ include_mentions: bool = True,
170
+ include_timelines: bool = False,
171
+ text_embedding_model_id: str = "xlm-roberta-base",
172
+ image_embedding_model_id: str = "google/vit-base-patch16-224-in21k",
173
+ dataset_path: Optional[Union[str, Path]] = None,
174
+ n_jobs: int = mp.cpu_count() - 1,
175
+ chunksize: int = 10,
176
+ verbose: bool = True,
177
+ ):
178
+ self.size = size
179
+ self.include_replies = include_replies
180
+ self.include_articles = include_articles
181
+ self.include_tweet_images = include_tweet_images
182
+ self.include_extra_images = include_extra_images
183
+ self.include_hashtags = include_hashtags
184
+ self.include_mentions = include_mentions
185
+ self.include_timelines = include_timelines
186
+ self.text_embedding_model_id = text_embedding_model_id
187
+ self.image_embedding_model_id = image_embedding_model_id
188
+ self.verbose = verbose
189
+
190
+ self.compiled: bool = False
191
+ self.rehydrated: bool = False
192
+ self.nodes: Dict[str, pd.DataFrame] = dict()
193
+ self.rels: Dict[Tuple[str, str, str], pd.DataFrame] = dict()
194
+
195
+ # Load the bearer token if it is not provided
196
+ if twitter_bearer_token is None:
197
+ twitter_bearer_token = os.environ.get("TWITTER_API_KEY")
198
+
199
+ # If no bearer token is available, raise a warning and set the `_twitter`
200
+ # attribute to None. Otherwise, set the `_twitter` attribute to a `Twitter`
201
+ # instance.
202
+ self._twitter: Twitter
203
+ if twitter_bearer_token is None:
204
+ warnings.warn(
205
+ "Twitter bearer token not provided, so rehydration can not be "
206
+ "performed. This is fine if you are using a pre-compiled MuMiN, but "
207
+ "if this is not the case then you will need to either specify the "
208
+ "`twitter_bearer_token` argument or set the environment variable "
209
+ "`TWITTER_API_KEY`."
210
+ )
211
+ else:
212
+ self._twitter = Twitter(twitter_bearer_token=twitter_bearer_token)
213
+
214
+ self._extractor = DataExtractor(
215
+ include_replies=include_replies,
216
+ include_articles=include_articles,
217
+ include_tweet_images=include_tweet_images,
218
+ include_extra_images=include_extra_images,
219
+ include_hashtags=include_hashtags,
220
+ include_mentions=include_mentions,
221
+ n_jobs=n_jobs,
222
+ chunksize=chunksize,
223
+ )
224
+ self._updator = IdUpdator()
225
+ self._embedder = Embedder(
226
+ text_embedding_model_id=text_embedding_model_id,
227
+ image_embedding_model_id=image_embedding_model_id,
228
+ include_articles=include_articles,
229
+ include_tweet_images=include_tweet_images,
230
+ include_extra_images=include_extra_images,
231
+ )
232
+
233
+ if dataset_path is None:
234
+ dataset_path = f"./mumin-{size}.zip"
235
+ self.dataset_path = Path(dataset_path)
236
+
237
+ # Set up logging verbosity
238
+ if self.verbose:
239
+ logger.setLevel(logging.INFO)
240
+ else:
241
+ logger.setLevel(logging.WARNING)
242
+
243
+ def compile(self, overwrite: bool = False):
244
+ """Compiles the dataset.
245
+
246
+ This entails downloading the dataset, rehydrating the Twitter data and
247
+ downloading the relevant associated data, such as articles and images.
248
+
249
+ Args:
250
+ overwrite (bool, optional):
251
+ Whether the dataset directory should be overwritten, in case it already
252
+ exists. Defaults to False.
253
+
254
+ Raises:
255
+ RuntimeError:
256
+ If the dataset needs to be compiled and a Twitter bearer token has not
257
+ been provided.
258
+ """
259
+ self._download(overwrite=overwrite)
260
+ self._load_dataset()
261
+
262
+ # Variable to check if dataset has been rehydrated and/or compiled
263
+ if "text" in self.nodes["tweet"].columns:
264
+ self.rehydrated = True
265
+ if self.rehydrated and str(self.nodes["tweet"].tweet_id.dtype) == "uint64":
266
+ self.compiled = True
267
+
268
+ # Only compile the dataset if it has not already been compiled
269
+ if not self.compiled:
270
+
271
+ # If the dataset has not already been rehydrated, rehydrate it
272
+ if not self.rehydrated:
273
+
274
+ # Shrink dataset to the correct size
275
+ self._shrink_dataset()
276
+
277
+ # If the bearer token is not available then raise an error
278
+ if not isinstance(self._twitter, Twitter):
279
+ raise RuntimeError(
280
+ "Twitter bearer token not provided. You need to either specify "
281
+ "the `twitter_bearer_token` argument in the `MuminDataset` "
282
+ "constructor or set the environment variable `TWITTER_API_KEY`."
283
+ )
284
+
285
+ # Rehydrate the tweets
286
+ self._rehydrate(node_type="tweet")
287
+ self._rehydrate(node_type="reply")
288
+
289
+ # Update the IDs of the data that was there pre-hydration
290
+ self.nodes, self.rels = self._updator.update_all(
291
+ nodes=self.nodes, rels=self.rels
292
+ )
293
+
294
+ # Save dataset
295
+ self._dump_dataset()
296
+
297
+ # Set the rehydrated flag to True
298
+ self.rehydrated = True
299
+
300
+ # Extract data from the rehydrated tweets
301
+ self.nodes, self.rels = self._extractor.extract_all(
302
+ nodes=self.nodes, rels=self.rels
303
+ )
304
+
305
+ # Filter the data
306
+ self._filter_node_features()
307
+ self._filter_relations()
308
+
309
+ # Set datatypes
310
+ self._set_datatypes()
311
+
312
+ # Remove unnecessary bits
313
+ self._remove_auxilliaries()
314
+ self._remove_islands()
315
+
316
+ # Save dataset
317
+ if not self.compiled:
318
+ self._dump_dataset()
319
+
320
+ # Mark dataset as compiled
321
+ self.compiled = True
322
+
323
+ return self
324
+
325
+ def _download(self, overwrite: bool = False):
326
+ """Downloads the dataset.
327
+
328
+ Args:
329
+ overwrite (bool, optional):
330
+ Whether the dataset directory should be overwritten, in case it already
331
+ exists. Defaults to False.
332
+ """
333
+ if not self.dataset_path.exists() or (self.dataset_path.exists() and overwrite):
334
+
335
+ logger.info("Downloading dataset")
336
+
337
+ # Remove existing directory if we are overwriting
338
+ if self.dataset_path.exists() and overwrite:
339
+ self.dataset_path.unlink()
340
+
341
+ # Set up download stream of dataset
342
+ with requests.get(self.download_url, stream=True) as response:
343
+
344
+ # If the response was unsuccessful then raise an error
345
+ if response.status_code != 200:
346
+ raise RuntimeError(f"[{response.status_code}] {response.content!r}")
347
+
348
+ # Download dataset with progress bar
349
+ total = int(response.headers["Content-Length"])
350
+ with tqdm(
351
+ total=total, unit="iB", unit_scale=True, desc="Downloading MuMiN"
352
+ ) as pbar:
353
+ with Path(self.dataset_path).open("wb") as f:
354
+ for data in response.iter_content(1024):
355
+ pbar.update(len(data))
356
+ f.write(data)
357
+
358
+ # The data.bris zip file contains two files: `mumin.zip` and
359
+ # `readme.txt`. We only want the first one, so we extract that and
360
+ # replace the original file with it.
361
+ with zipfile.ZipFile(
362
+ self.dataset_path, mode="r", compression=zipfile.ZIP_DEFLATED
363
+ ) as zipf:
364
+ zipdata = zipf.read("23yv276we2mll25fjakkfim2ml/mumin.zip")
365
+ with Path(self.dataset_path).open("wb") as f:
366
+ f.write(zipdata)
367
+
368
+ logger.info("Converting dataset to less compressed format")
369
+
370
+ # Open the zip file containing the dataset
371
+ data_dict = dict()
372
+ with zipfile.ZipFile(
373
+ self.dataset_path, mode="r", compression=zipfile.ZIP_DEFLATED
374
+ ) as zip_file:
375
+
376
+ # Loop over all the files in the zipped file
377
+ for name in zip_file.namelist():
378
+
379
+ # Extract the dataframe in the file
380
+ byte_data = zip_file.read(name=name)
381
+ df = pd.read_pickle(io.BytesIO(byte_data), compression="xz")
382
+ data_dict[name] = df
383
+
384
+ # Overwrite the zip file in a less compressed way, to make io operations
385
+ # faster
386
+ with zipfile.ZipFile(
387
+ self.dataset_path, mode="w", compression=zipfile.ZIP_STORED
388
+ ) as zip_file:
389
+ for name, df in data_dict.items():
390
+ buffer = io.BytesIO()
391
+ df.to_pickle(buffer, protocol=4)
392
+ zip_file.writestr(name, data=buffer.getvalue())
393
+
394
+ return self
395
+
396
+ def _load_dataset(self):
397
+ """Loads the dataset files into memory.
398
+
399
+ Raises:
400
+ RuntimeError:
401
+ If the dataset has not been downloaded yet.
402
+ """
403
+ # Raise error if the dataset has not been downloaded yet
404
+ if not self.dataset_path.exists():
405
+ raise RuntimeError("Dataset has not been downloaded yet!")
406
+
407
+ logger.info("Loading dataset")
408
+
409
+ # Reset `nodes` and `relations` to ensure a fresh start
410
+ self.nodes = dict()
411
+ self.rels = dict()
412
+
413
+ # Open the zip file containing the dataset
414
+ with zipfile.ZipFile(
415
+ self.dataset_path, mode="r", compression=zipfile.ZIP_STORED
416
+ ) as zip_file:
417
+
418
+ # Loop over all the files in the zipped file
419
+ for name in zip_file.namelist():
420
+
421
+ # Extract the dataframe in the file
422
+ byte_data = zip_file.read(name=name)
423
+ df = pd.read_pickle(io.BytesIO(byte_data))
424
+
425
+ # If there are no underscores in the filename then we assume that it
426
+ # contains node data
427
+ if "_" not in name:
428
+ self.nodes[name.replace(".pickle", "")] = df.copy()
429
+
430
+ # Otherwise, with underscores in the filename then we assume it
431
+ # contains relation data
432
+ else:
433
+ splits = name.replace(".pickle", "").split("_")
434
+ src = splits[0]
435
+ tgt = splits[-1]
436
+ rel = "_".join(splits[1:-1])
437
+ self.rels[(src, rel, tgt)] = df.copy()
438
+
439
+ # Ensure that claims are present in the dataset
440
+ if "claim" not in self.nodes.keys():
441
+ raise RuntimeError("No claims are present in the file!")
442
+
443
+ # Ensure that tweets are present in the dataset, and also that the tweet
444
+ # IDs are unique
445
+ if "tweet" not in self.nodes.keys():
446
+ raise RuntimeError("No tweets are present in the file!")
447
+ else:
448
+ tweet_df = self.nodes["tweet"]
449
+ duplicated = tweet_df[tweet_df.tweet_id.duplicated()].tweet_id.tolist()
450
+ if len(duplicated) > 0:
451
+ raise RuntimeError(
452
+ f"The tweet IDs {duplicated} are " f"duplicate in the dataset!"
453
+ )
454
+
455
+ return self
456
+
457
+ def _shrink_dataset(self):
458
+ """Shrink dataset if `size` is 'small' or 'medium"""
459
+ logger.info("Shrinking dataset")
460
+
461
+ # Define the `relevance` threshold
462
+ if self.size == "small":
463
+ threshold = 0.80 # noqa
464
+ elif self.size == "medium":
465
+ threshold = 0.75 # noqa
466
+ elif self.size == "large":
467
+ threshold = 0.70 # noqa
468
+ elif self.size == "test":
469
+ threshold = 0.995 # noqa
470
+
471
+ # Filter nodes
472
+ ntypes = ["tweet", "reply", "user", "article"]
473
+ for ntype in ntypes:
474
+ self.nodes[ntype] = (
475
+ self.nodes[ntype]
476
+ .query("relevance > @threshold")
477
+ .drop(columns=["relevance"])
478
+ .reset_index(drop=True)
479
+ )
480
+
481
+ # Filter relations
482
+ etypes = [
483
+ ("reply", "reply_to", "tweet"),
484
+ ("reply", "quote_of", "tweet"),
485
+ ("user", "retweeted", "tweet"),
486
+ ("user", "follows", "user"),
487
+ ("tweet", "discusses", "claim"),
488
+ ("article", "discusses", "claim"),
489
+ ]
490
+ for etype in etypes:
491
+ self.rels[etype] = (
492
+ self.rels[etype]
493
+ .query("relevance > @threshold")
494
+ .drop(columns=["relevance"])
495
+ .reset_index(drop=True)
496
+ )
497
+
498
+ # Filter claims
499
+ claim_df = self.nodes["claim"]
500
+ discusses_rel = self.rels[("tweet", "discusses", "claim")]
501
+ include_claim = claim_df.id.isin(discusses_rel.tgt.tolist())
502
+ self.nodes["claim"] = claim_df[include_claim].reset_index(drop=True)
503
+
504
+ # Filter timeline tweets
505
+ if not self.include_timelines:
506
+ src_tweet_ids = (
507
+ self.rels[("tweet", "discusses", "claim")]
508
+ .src.astype(np.uint64)
509
+ .tolist()
510
+ )
511
+ is_src = self.nodes["tweet"].tweet_id.isin(src_tweet_ids)
512
+ self.nodes["tweet"] = self.nodes["tweet"].loc[is_src]
513
+
514
+ return self
515
+
516
+ def _rehydrate(self, node_type: str):
517
+ """Rehydrate the tweets and users in the dataset.
518
+
519
+ Args:
520
+ node_type (str): The type of node to rehydrate.
521
+ """
522
+
523
+ if node_type in self.nodes.keys() and (
524
+ node_type != "reply" or self.include_replies
525
+ ):
526
+
527
+ logger.info(f"Rehydrating {node_type} nodes")
528
+
529
+ # Get the tweet IDs, and if the node type is a tweet then separate these
530
+ # into source tweets and the rest (i.e., timeline tweets)
531
+ if node_type == "tweet":
532
+ source_tweet_ids = (
533
+ self.rels[("tweet", "discusses", "claim")]
534
+ .src.astype(np.uint64)
535
+ .tolist()
536
+ )
537
+ tweet_ids = [
538
+ tweet_id
539
+ for tweet_id in self.nodes[node_type].tweet_id.astype(np.uint64)
540
+ if tweet_id not in source_tweet_ids
541
+ ]
542
+ else:
543
+ source_tweet_ids = list()
544
+ tweet_ids = self.nodes[node_type].tweet_id.astype(np.uint64).tolist()
545
+
546
+ # Store any features the nodes might have had before hydration
547
+ prehydration_df = self.nodes[node_type].copy()
548
+
549
+ # Rehydrate the source tweets
550
+ if len(source_tweet_ids) > 0:
551
+ params = dict(tweet_ids=source_tweet_ids)
552
+ source_tweet_dfs = self._twitter.rehydrate_tweets(**params)
553
+
554
+ # Return error if there are no tweets were rehydrated. This is probably
555
+ # because the bearer token is wrong
556
+ if len(source_tweet_dfs) == 0:
557
+ raise RuntimeError(
558
+ "No tweets were rehydrated. Check if the bearer token is "
559
+ "correct."
560
+ )
561
+
562
+ if len(tweet_ids) == 0:
563
+ tweet_dfs = {key: pd.DataFrame() for key in source_tweet_dfs.keys()}
564
+
565
+ # Rehydrate the other tweets
566
+ if len(tweet_ids) > 0:
567
+ params = dict(tweet_ids=tweet_ids)
568
+ tweet_dfs = self._twitter.rehydrate_tweets(**params)
569
+
570
+ # Return error if there are no tweets were rehydrated. This is
571
+ # probably because the bearer token is wrong
572
+ if len(tweet_dfs) == 0:
573
+ raise RuntimeError(
574
+ "No tweets were rehydrated. Check if "
575
+ "the bearer token is correct."
576
+ )
577
+
578
+ if len(source_tweet_ids) == 0:
579
+ source_tweet_dfs = {key: pd.DataFrame() for key in tweet_dfs.keys()}
580
+
581
+ # Extract and store tweets and users
582
+ tweet_df = pd.concat(
583
+ [source_tweet_dfs["tweets"], tweet_dfs["tweets"]], ignore_index=True
584
+ )
585
+ self.nodes[node_type] = tweet_df.drop_duplicates(
586
+ subset="tweet_id"
587
+ ).reset_index(drop=True)
588
+ user_df = pd.concat(
589
+ [source_tweet_dfs["users"], tweet_dfs["users"]], ignore_index=True
590
+ )
591
+ if "user" in self.nodes.keys() and "username" in self.nodes["user"].columns:
592
+ user_df = (
593
+ pd.concat((self.nodes["user"], user_df), axis=0)
594
+ .drop_duplicates(subset="user_id")
595
+ .reset_index(drop=True)
596
+ )
597
+ self.nodes["user"] = user_df
598
+
599
+ # Add prehydration tweet features back to the tweets
600
+ self.nodes[node_type] = (
601
+ self.nodes[node_type]
602
+ .merge(prehydration_df, on="tweet_id", how="outer")
603
+ .reset_index(drop=True)
604
+ )
605
+
606
+ # Extract and store images
607
+ # Note: This will store `self.nodes['image']`, but this is only to enable
608
+ # extraction of URLs later on. The `self.nodes['image']` will be
609
+ # overwritten later on.
610
+ if (
611
+ node_type == "tweet"
612
+ and self.include_tweet_images
613
+ and len(source_tweet_dfs["media"])
614
+ ):
615
+
616
+ image_df = (
617
+ source_tweet_dfs["media"]
618
+ .query('type == "photo"')
619
+ .drop_duplicates(subset="media_key")
620
+ .reset_index(drop=True)
621
+ )
622
+
623
+ if "image" in self.nodes.keys():
624
+ image_df = (
625
+ pd.concat((self.nodes["image"], image_df), axis=0)
626
+ .drop_duplicates(subset="media_key")
627
+ .reset_index(drop=True)
628
+ )
629
+
630
+ self.nodes["image"] = image_df
631
+
632
+ return self
633
+
634
+ def add_embeddings(
635
+ self,
636
+ nodes_to_embed: List[str] = [
637
+ "tweet",
638
+ "reply",
639
+ "user",
640
+ "claim",
641
+ "article",
642
+ "image",
643
+ ],
644
+ ):
645
+ """Computes, stores and dumps embeddings of node features.
646
+
647
+ Args:
648
+ nodes_to_embed (list of str):
649
+ The node types which needs to be embedded. If a node type does not
650
+ exist in the graph it will be ignored. Defaults to ['tweet', 'reply',
651
+ 'user', 'claim', 'article', 'image'].
652
+ """
653
+ # Compute the embeddings
654
+ self.nodes, embeddings_added = self._embedder.embed_all(
655
+ nodes=self.nodes, nodes_to_embed=nodes_to_embed
656
+ )
657
+
658
+ # Store dataset if any embeddings were added
659
+ if embeddings_added:
660
+ self._dump_dataset()
661
+
662
+ return self
663
+
664
+ def _filter_node_features(self):
665
+ """Filters the node features to avoid redundancies and noise"""
666
+ logger.info("Filters node features")
667
+
668
+ # Set up the node features that should be kept
669
+ size = "small" if self.size == "test" else self.size
670
+ node_feats = dict(
671
+ claim=[
672
+ "embedding",
673
+ "label",
674
+ "reviewers",
675
+ "date",
676
+ "language",
677
+ "keywords",
678
+ "cluster_keywords",
679
+ "cluster",
680
+ f"{size}_train_mask",
681
+ f"{size}_val_mask",
682
+ f"{size}_test_mask",
683
+ ],
684
+ tweet=[
685
+ "tweet_id",
686
+ "text",
687
+ "created_at",
688
+ "lang",
689
+ "source",
690
+ "public_metrics.retweet_count",
691
+ "public_metrics.reply_count",
692
+ "public_metrics.quote_count",
693
+ "label",
694
+ f"{size}_train_mask",
695
+ f"{size}_val_mask",
696
+ f"{size}_test_mask",
697
+ ],
698
+ reply=[
699
+ "tweet_id",
700
+ "text",
701
+ "created_at",
702
+ "lang",
703
+ "source",
704
+ "public_metrics.retweet_count",
705
+ "public_metrics.reply_count",
706
+ "public_metrics.quote_count",
707
+ ],
708
+ user=[
709
+ "user_id",
710
+ "verified",
711
+ "protected",
712
+ "created_at",
713
+ "username",
714
+ "description",
715
+ "url",
716
+ "name",
717
+ "public_metrics.followers_count",
718
+ "public_metrics.following_count",
719
+ "public_metrics.tweet_count",
720
+ "public_metrics.listed_count",
721
+ "location",
722
+ ],
723
+ image=["url", "pixels", "width", "height"],
724
+ article=["url", "title", "content"],
725
+ place=[
726
+ "place_id",
727
+ "name",
728
+ "full_name",
729
+ "country_code",
730
+ "country",
731
+ "place_type",
732
+ "lat",
733
+ "lng",
734
+ ],
735
+ hashtag=["tag"],
736
+ poll=[
737
+ "poll_id",
738
+ "labels",
739
+ "votes",
740
+ "end_datetime",
741
+ "voting_status",
742
+ "duration_minutes",
743
+ ],
744
+ )
745
+
746
+ # Set up renaming of node features that should be kept
747
+ node_feat_renaming = {
748
+ "public_metrics.retweet_count": "num_retweets",
749
+ "public_metrics.reply_count": "num_replies",
750
+ "public_metrics.quote_count": "num_quote_tweets",
751
+ "public_metrics.followers_count": "num_followers",
752
+ "public_metrics.following_count": "num_followees",
753
+ "public_metrics.tweet_count": "num_tweets",
754
+ "public_metrics.listed_count": "num_listed",
755
+ f"{size}_train_mask": "train_mask",
756
+ f"{size}_val_mask": "val_mask",
757
+ f"{size}_test_mask": "test_mask",
758
+ }
759
+
760
+ # Filter and rename the node features
761
+ for node_type, features in node_feats.items():
762
+ if node_type in self.nodes.keys():
763
+ filtered_feats = [
764
+ feat for feat in features if feat in self.nodes[node_type].columns
765
+ ]
766
+ renaming_dict = {
767
+ old: new
768
+ for old, new in node_feat_renaming.items()
769
+ if old in features
770
+ }
771
+ self.nodes[node_type] = self.nodes[node_type][filtered_feats].rename(
772
+ columns=renaming_dict
773
+ )
774
+
775
+ return self
776
+
777
+ def _filter_relations(self):
778
+ """Filters the relations to only include node IDs that exist"""
779
+ logger.info("Filters relations")
780
+
781
+ # Remove article relations if they are not included
782
+ if not self.include_articles:
783
+ rels_to_pop = list()
784
+ for rel_type in self.rels.keys():
785
+ src, _, tgt = rel_type
786
+ if src == "article" or tgt == "article":
787
+ rels_to_pop.append(rel_type)
788
+ for rel_type in rels_to_pop:
789
+ self.rels.pop(rel_type)
790
+
791
+ # Remove reply relations if they are not included
792
+ if not self.include_replies:
793
+ rels_to_pop = list()
794
+ for rel_type in self.rels.keys():
795
+ src, _, tgt = rel_type
796
+ if src == "reply" or tgt == "reply":
797
+ rels_to_pop.append(rel_type)
798
+ for rel_type in rels_to_pop:
799
+ self.rels.pop(rel_type)
800
+
801
+ # Remove mention relations if they are not included
802
+ if not self.include_mentions:
803
+ rels_to_pop = list()
804
+ for rel_type in self.rels.keys():
805
+ _, rel, _ = rel_type
806
+ if rel == "mentions":
807
+ rels_to_pop.append(rel_type)
808
+ for rel_type in rels_to_pop:
809
+ self.rels.pop(rel_type)
810
+
811
+ # Loop over the relations, extract the associated node IDs and filter the
812
+ # relation dataframe to only include relations between nodes that exist
813
+ rels_to_pop = list()
814
+ for rel_type, rel_df in self.rels.items():
815
+
816
+ # Pop the relation if the dataframe does not exist
817
+ if rel_df is None or len(rel_df) == 0:
818
+ rels_to_pop.append(rel_type)
819
+ continue
820
+
821
+ # Pop the relation if the source or target node does not exist
822
+ src, _, tgt = rel_type
823
+ if src not in self.nodes.keys() or tgt not in self.nodes.keys():
824
+ rels_to_pop.append(rel_type)
825
+
826
+ # Otherwise filter the relation dataframe to only include nodes that exist
827
+ else:
828
+ src_ids = self.nodes[src].index.tolist()
829
+ tgt_ids = self.nodes[tgt].index.tolist()
830
+ rel_df = rel_df[rel_df.src.isin(src_ids)]
831
+ rel_df = rel_df[rel_df.tgt.isin(tgt_ids)]
832
+ self.rels[rel_type] = rel_df
833
+
834
+ # Pop the relations that has been assigned to be popped
835
+ for rel_type in rels_to_pop:
836
+ self.rels.pop(rel_type)
837
+
838
+ def _set_datatypes(self):
839
+ """Set datatypes in the dataframes, to use less memory"""
840
+
841
+ # Set up all the dtypes of the columns
842
+ dtypes = dict(
843
+ tweet=dict(
844
+ tweet_id="uint64",
845
+ text="str",
846
+ created_at={"created_at": "datetime64[ns]"},
847
+ lang="category",
848
+ source="str",
849
+ num_retweets="uint64",
850
+ num_replies="uint64",
851
+ num_quote_tweets="uint64",
852
+ ),
853
+ user=dict(
854
+ user_id="uint64",
855
+ verified="bool",
856
+ protected="bool",
857
+ created_at={"created_at": "datetime64[ns]"},
858
+ username="str",
859
+ description="str",
860
+ url="str",
861
+ name="str",
862
+ num_followers="uint64",
863
+ num_followees="uint64",
864
+ num_tweets="uint64",
865
+ num_listed="uint64",
866
+ location="category",
867
+ ),
868
+ )
869
+
870
+ if self.include_hashtags:
871
+ dtypes["hashtag"] = dict(tag="str")
872
+
873
+ if self.include_replies:
874
+ dtypes["reply"] = dict(
875
+ tweet_id="uint64",
876
+ text="str",
877
+ created_at={"created_at": "datetime64[ns]"},
878
+ lang="category",
879
+ source="str",
880
+ num_retweets="uint64",
881
+ num_replies="uint64",
882
+ num_quote_tweets="uint64",
883
+ )
884
+
885
+ if self.include_tweet_images or self.include_extra_images:
886
+ dtypes["image"] = dict(
887
+ url="str", pixels="numpy:uint8", width="uint64", height="uint64"
888
+ )
889
+
890
+ if self.include_articles:
891
+ dtypes["article"] = dict(url="str", title="str", content="str")
892
+
893
+ # Create conversion function for missing values
894
+ def fill_na_values(dtype: Union[str, dict]):
895
+ if dtype == "uint64":
896
+ return 0
897
+ elif dtype == "bool":
898
+ return False
899
+ elif dtype == dict(created_at="datetime64[ns]"):
900
+ return np.datetime64("NaT")
901
+ elif dtype == "category":
902
+ return "NaN"
903
+ elif dtype == "str":
904
+ return ""
905
+ else:
906
+ return np.nan
907
+
908
+ # Loop over all nodes
909
+ for ntype, dtype_dict in dtypes.items():
910
+ if ntype in self.nodes.keys():
911
+
912
+ # Set the dtypes for non-numpy columns
913
+ dtype_dict_no_numpy = {
914
+ col: dtype
915
+ for col, dtype in dtype_dict.items()
916
+ if not isinstance(dtype, str) or not dtype.startswith("numpy")
917
+ }
918
+ for col, dtype in dtype_dict_no_numpy.items():
919
+ if col in self.nodes[ntype].columns:
920
+
921
+ # Fill NaN values with canonical values in accordance with the
922
+ # datatype
923
+ self.nodes[ntype][col].fillna(
924
+ fill_na_values(dtype), inplace=True
925
+ )
926
+
927
+ # Set the dtype
928
+ self.nodes[ntype][col] = self.nodes[ntype][col].astype(dtype)
929
+
930
+ # For numpy columns, set the type manually
931
+ def numpy_fn(x, dtype: str):
932
+ return np.asarray(x, dtype=dtype)
933
+
934
+ for col, dtype in dtype_dict.items():
935
+ if (
936
+ isinstance(dtype, str)
937
+ and dtype.startswith("numpy")
938
+ and col in self.nodes[ntype].columns
939
+ ):
940
+
941
+ # Fill NaN values with canonical values in accordance with the
942
+ # datatype
943
+ self.nodes[ntype][col].fillna(
944
+ fill_na_values(dtype), inplace=True
945
+ )
946
+
947
+ # Extract the NumPy datatype
948
+ numpy_dtype = dtype.split(":")[-1]
949
+
950
+ # Tweak the numpy function to include the datatype
951
+ fn = partial(numpy_fn, dtype=numpy_dtype)
952
+
953
+ # Set the dtype
954
+ self.nodes[ntype][col] = self.nodes[ntype][col].map(fn)
955
+
956
+ def _remove_auxilliaries(self):
957
+ """Removes node types that are not in use anymore"""
958
+ # Remove auxilliary node types
959
+ nodes_to_remove = [
960
+ node_type
961
+ for node_type in self.nodes.keys()
962
+ if node_type not in self._node_dump
963
+ ]
964
+ for node_type in nodes_to_remove:
965
+ self.nodes.pop(node_type)
966
+
967
+ # Remove auxilliary relation types
968
+ rels_to_remove = [
969
+ rel_type for rel_type in self.rels.keys() if rel_type not in self._rel_dump
970
+ ]
971
+ for rel_type in rels_to_remove:
972
+ self.rels.pop(rel_type)
973
+
974
+ return self
975
+
976
+ def _remove_islands(self):
977
+ """Removes nodes and relations that are not connected to anything"""
978
+
979
+ # Loop over all the node types
980
+ for node_type, node_df in self.nodes.items():
981
+
982
+ # For each node type, loop over all the relations, to see what nodes of
983
+ # that node type does not appear in any of the relations
984
+ for rel_type, rel_df in self.rels.items():
985
+ src, _, tgt = rel_type
986
+
987
+ # If the node is the source of the relation
988
+ if node_type == src:
989
+
990
+ # Store all the nodes connected to the relation (or any of the
991
+ # previously checked relations)
992
+ connected = node_df.index.isin(rel_df.src.tolist())
993
+ if "connected" in node_df.columns:
994
+ connected = node_df.connected | connected
995
+ node_df["connected"] = connected
996
+
997
+ # If the node is the source of the relation
998
+ if node_type == tgt:
999
+
1000
+ # Store all the nodes connected to the relation (or any of the
1001
+ # previously checked relations)
1002
+ connected = node_df.index.isin(rel_df.tgt.tolist())
1003
+ if "connected" in node_df.columns:
1004
+ connected = node_df.connected | connected
1005
+ node_df["connected"] = connected
1006
+
1007
+ # Filter the node dataframe to only keep the connected ones
1008
+ if "connected" in node_df.columns and "index" not in node_df.columns:
1009
+ self.nodes[node_type] = (
1010
+ node_df.query("connected == True")
1011
+ .drop(columns="connected")
1012
+ .reset_index()
1013
+ )
1014
+
1015
+ # Update the relevant relations
1016
+ for rel_type, rel_df in self.rels.items():
1017
+ src, _, tgt = rel_type
1018
+
1019
+ # If islands have been removed from the source, then update those
1020
+ # indices
1021
+ if node_type == src and "index" in self.nodes[node_type]:
1022
+ node_df = (
1023
+ self.nodes[node_type]
1024
+ .rename(columns=dict(index="old_idx"))
1025
+ .reset_index()
1026
+ )
1027
+
1028
+ rel_df = (
1029
+ rel_df.merge(
1030
+ node_df[["index", "old_idx"]],
1031
+ left_on="src",
1032
+ right_on="old_idx",
1033
+ )
1034
+ .drop(columns=["src", "old_idx"])
1035
+ .rename(columns=dict(index="src"))
1036
+ )
1037
+ self.rels[rel_type] = rel_df[["src", "tgt"]]
1038
+ self.nodes[node_type] = self.nodes[node_type]
1039
+
1040
+ # If islands have been removed from the target, then update those
1041
+ # indices
1042
+ if node_type == tgt and "index" in self.nodes[node_type]:
1043
+ node_df = (
1044
+ self.nodes[node_type]
1045
+ .rename(columns=dict(index="old_idx"))
1046
+ .reset_index()
1047
+ )
1048
+ rel_df = (
1049
+ rel_df.merge(
1050
+ node_df[["index", "old_idx"]],
1051
+ left_on="tgt",
1052
+ right_on="old_idx",
1053
+ )
1054
+ .drop(columns=["tgt", "old_idx"])
1055
+ .rename(columns=dict(index="tgt"))
1056
+ )
1057
+ self.rels[rel_type] = rel_df[["src", "tgt"]]
1058
+ self.nodes[node_type] = self.nodes[node_type]
1059
+
1060
+ if "index" in self.nodes[node_type]:
1061
+ self.nodes[node_type] = self.nodes[node_type].drop(columns="index")
1062
+
1063
+ return self
1064
+
1065
+ def _dump_dataset(self):
1066
+ """Dumps the dataset to a zip file"""
1067
+ logger.info("Dumping dataset")
1068
+
1069
+ # Create a temporary pickle folder
1070
+ temp_pickle_folder = Path("temp_pickle_folder")
1071
+ if not temp_pickle_folder.exists():
1072
+ temp_pickle_folder.mkdir()
1073
+
1074
+ # Make temporary pickle list
1075
+ pickle_list = list()
1076
+
1077
+ # Create progress bar
1078
+ total = len(self._node_dump) + len(self._rel_dump) + 1
1079
+ pbar = tqdm(total=total)
1080
+
1081
+ # Store the nodes
1082
+ for node_type in self._node_dump:
1083
+ pbar.set_description(f"Storing {node_type} nodes")
1084
+ if node_type in self.nodes.keys():
1085
+ pickle_list.append(node_type)
1086
+ pickle_path = temp_pickle_folder / f"{node_type}.pickle"
1087
+ self.nodes[node_type].to_pickle(pickle_path, protocol=4)
1088
+ pbar.update()
1089
+
1090
+ # Store the relations
1091
+ for rel_type in self._rel_dump:
1092
+ pbar.set_description(f"Storing {rel_type} relations")
1093
+ if rel_type in self.rels.keys():
1094
+ name = "_".join(rel_type)
1095
+ pickle_list.append(name)
1096
+ pickle_path = temp_pickle_folder / f"{name}.pickle"
1097
+ self.rels[rel_type].to_pickle(pickle_path, protocol=4)
1098
+ pbar.update()
1099
+
1100
+ # Zip the nodes and relations, and save the zip file
1101
+ with zipfile.ZipFile(
1102
+ self.dataset_path, mode="w", compression=zipfile.ZIP_STORED
1103
+ ) as zip_file:
1104
+ pbar.set_description("Dumping dataset")
1105
+ for name in pickle_list:
1106
+ fname = f"{name}.pickle"
1107
+ zip_file.write(temp_pickle_folder / fname, arcname=fname)
1108
+
1109
+ # Remove the temporary pickle folder
1110
+ rmtree(temp_pickle_folder)
1111
+
1112
+ # Final progress bar update and close it
1113
+ pbar.update()
1114
+ pbar.close()
1115
+
1116
+ return self
1117
+
1118
+ def to_dgl(self):
1119
+ """Convert the dataset to a DGL dataset.
1120
+
1121
+ Returns:
1122
+ DGLHeteroGraph:
1123
+ The graph in DGL format.
1124
+ """
1125
+ logger.info("Outputting to DGL")
1126
+ return build_dgl_dataset(nodes=self.nodes, relations=self.rels)
1127
+
1128
+ def __repr__(self) -> str:
1129
+ """A string representation of the dataset.
1130
+
1131
+ Returns:
1132
+ str: The representation of the dataset.
1133
+ """
1134
+ bearer_token_available = self._twitter is not None
1135
+ if len(self.nodes) == 0 or len(self.rels) == 0:
1136
+ return (
1137
+ f"MuminDataset(size={self.size}, "
1138
+ f"rehydrated={self.rehydrated}, "
1139
+ f"compiled={self.compiled}, "
1140
+ f"bearer_token_available={bearer_token_available})"
1141
+ )
1142
+ else:
1143
+ num_nodes = sum([len(df) for df in self.nodes.values()])
1144
+ num_rels = sum([len(df) for df in self.rels.values()])
1145
+ return (
1146
+ f"MuminDataset(num_nodes={num_nodes:,}, "
1147
+ f"num_relations={num_rels:,}, "
1148
+ f"size='{self.size}', "
1149
+ f"rehydrated={self.rehydrated}, "
1150
+ f"compiled={self.compiled}, "
1151
+ f"bearer_token_available={bearer_token_available})"
1152
+ )
src/mumin/dgl.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to exporting the dataset to the Deep Graph Library"""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Dict, Tuple, Union
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from torch import Tensor
10
+
11
+
12
+ def build_dgl_dataset(
13
+ nodes: Dict[str, pd.DataFrame], relations: Dict[Tuple[str, str, str], pd.DataFrame]
14
+ ):
15
+ """Convert the dataset to a DGL graph.
16
+
17
+ This assumes that the dataset has been compiled and thus also dumped to a local
18
+ file.
19
+
20
+ Args:
21
+ nodes (dict):
22
+ The nodes of the dataset, with keys the node types and NumPy arrays as the
23
+ values.
24
+ relations (dict):
25
+ The relations of the dataset, with keys being triples of strings
26
+ (source_node_type, relation_type, target_node_type) and NumPy arrays as the
27
+ values.
28
+
29
+ Returns:
30
+ DGLHeteroGraph:
31
+ The graph in DGL format.
32
+
33
+ Raises:
34
+ ModuleNotFoundError:
35
+ If `dgl` has not been installed.
36
+ """
37
+ # Import the needed libraries, and raise an error if they have not yet been
38
+ # installed
39
+ try:
40
+ import dgl
41
+ import torch
42
+ except ModuleNotFoundError:
43
+ raise ModuleNotFoundError(
44
+ "Could not find the `dgl` library. Please install it and try again."
45
+ )
46
+
47
+ # Remove the claims that are only connected to deleted tweets
48
+ tweet_df = nodes["tweet"].dropna()
49
+ claim_df = nodes["claim"]
50
+ discusses_df = relations[("tweet", "discusses", "claim")]
51
+ discusses_df = discusses_df[discusses_df.src.isin(tweet_df.index.tolist())]
52
+ claim_df = claim_df[claim_df.index.isin(discusses_df.tgt.tolist())]
53
+ nodes["claim"] = claim_df
54
+
55
+ # Set up the graph as a DGL graph
56
+ graph_data = dict()
57
+ for canonical_etype, rel_arr in relations.items():
58
+
59
+ # Drop the NaN nodes, corresponding to the deleted tweets. We also reset the
60
+ # indices to start from 0, as DGL requires there to be no gaps in the indexing
61
+ src, rel, tgt = canonical_etype
62
+ allowed_src = (
63
+ nodes[src]
64
+ .dropna()
65
+ .reset_index()
66
+ .rename(columns=dict(index="old_idx"))
67
+ .old_idx
68
+ )
69
+ allowed_src = {old: new for new, old in allowed_src.iteritems()}
70
+ allowed_tgt = (
71
+ nodes[tgt]
72
+ .dropna()
73
+ .reset_index()
74
+ .rename(columns=dict(index="old_idx"))
75
+ .old_idx
76
+ )
77
+ allowed_tgt = {old: new for new, old in allowed_tgt.iteritems()}
78
+
79
+ # Get a dataframe containing the edges between allowed source and target nodes
80
+ # (i.e., non-deleted)
81
+ rel_arr = (
82
+ relations[canonical_etype][["src", "tgt"]]
83
+ .query("src in @allowed_src.keys() and " "tgt in @allowed_tgt.keys()")
84
+ .drop_duplicates()
85
+ )
86
+
87
+ # Convert the node indices in the edge dataframe to the new indices without
88
+ # gaps
89
+ rel_arr.src = [allowed_src[old_idx] for old_idx in rel_arr.src.tolist()]
90
+ rel_arr.tgt = [allowed_tgt[old_idx] for old_idx in rel_arr.tgt.tolist()]
91
+
92
+ # Convert the edge dataframe to a NumPy array
93
+ rel_arr = rel_arr.to_numpy()
94
+
95
+ # If there are edges left in the edge array, then convert these to PyTorch
96
+ # tensors and add them to the graph data
97
+ if rel_arr.size:
98
+ src_tensor = torch.from_numpy(rel_arr[:, 0]).long()
99
+ tgt_tensor = torch.from_numpy(rel_arr[:, 1]).long()
100
+ graph_data[canonical_etype] = (src_tensor, tgt_tensor)
101
+
102
+ # Adding inverse relations as well, to ensure that graph is bidirected
103
+ graph_data[(tgt, f"{rel}_inv", src)] = (tgt_tensor, src_tensor)
104
+
105
+ # Initialise a DGL heterogeneous graph from the graph data
106
+ dgl_graph = dgl.heterograph(graph_data)
107
+
108
+ def emb_to_tensor(df: pd.DataFrame, col_name: str) -> torch.Tensor:
109
+ """Convenience function converting embeddings to tensors.
110
+
111
+ Args:
112
+ df (pd.DataFrame):
113
+ The dataframe containing the embeddings.
114
+ col_name (str):
115
+ The name of the column containing the embeddings.
116
+
117
+ Returns:
118
+ torch.Tensor:
119
+ The embeddings as a PyTorch tensor.
120
+ """
121
+ if type(df[col_name].iloc[0]) == str:
122
+ df[col_name] = df[col_name].map(lambda x: json.loads(x))
123
+ np_array = np.stack(df[col_name].tolist())
124
+ if len(np_array.shape) == 1:
125
+ np_array = np.expand_dims(np_array, axis=1)
126
+ return torch.from_numpy(np_array)
127
+
128
+ # Initialise `tensors` variable
129
+ tensors: Union[Tuple[Tensor], Tuple[Tensor, Tensor], Tuple[Tensor, Tensor, Tensor]]
130
+
131
+ # Add node features to the Tweet nodes
132
+ allowed_tweet_df = nodes["tweet"].dropna().reset_index(drop=True)
133
+ cols = ["num_retweets", "num_replies", "num_quote_tweets"]
134
+ tweet_feats = torch.from_numpy(allowed_tweet_df[cols].astype(float).to_numpy())
135
+ if (
136
+ "text_emb" in allowed_tweet_df.columns
137
+ and "lang_emb" in allowed_tweet_df.columns
138
+ ):
139
+ tweet_embs = emb_to_tensor(allowed_tweet_df, "text_emb")
140
+ lang_embs = emb_to_tensor(allowed_tweet_df, "lang_emb")
141
+ tensors = (tweet_embs, lang_embs, tweet_feats)
142
+ else:
143
+ tensors = (tweet_feats,)
144
+ dgl_graph.nodes["tweet"].data["feat"] = torch.cat(tensors, dim=1)
145
+
146
+ # Add node features to the Reply nodes
147
+ if "reply" in nodes.keys() and "reply" in dgl_graph.ntypes:
148
+ allowed_reply_df = nodes["reply"].dropna().reset_index(drop=True)
149
+ cols = ["num_retweets", "num_replies", "num_quote_tweets"]
150
+ reply_feats = torch.from_numpy(allowed_reply_df[cols].astype(float).to_numpy())
151
+ if (
152
+ "text_emb" in allowed_reply_df.columns
153
+ and "lang_emb" in allowed_reply_df.columns
154
+ ):
155
+ reply_embs = emb_to_tensor(allowed_reply_df, "text_emb")
156
+ lang_embs = emb_to_tensor(allowed_reply_df, "lang_emb")
157
+ tensors = (reply_embs, lang_embs, reply_feats)
158
+ else:
159
+ tensors = (reply_feats,)
160
+ dgl_graph.nodes["reply"].data["feat"] = torch.cat(tensors, dim=1)
161
+
162
+ # Add node features to the User nodes
163
+ nodes["user"]["verified"] = nodes["user"].verified.astype(np.uint64)
164
+ nodes["user"]["protected"] = nodes["user"].verified.astype(np.uint64)
165
+ cols = [
166
+ "verified",
167
+ "protected",
168
+ "num_followers",
169
+ "num_followees",
170
+ "num_tweets",
171
+ "num_listed",
172
+ ]
173
+ user_feats = torch.from_numpy(nodes["user"][cols].astype(float).to_numpy())
174
+ if "description_emb" in nodes["user"].columns:
175
+ user_embs = emb_to_tensor(nodes["user"], "description_emb")
176
+ tensors = (user_embs, user_feats)
177
+ else:
178
+ tensors = (user_feats,)
179
+ dgl_graph.nodes["user"].data["feat"] = torch.cat(tensors, dim=1)
180
+
181
+ # Add node features to the Article nodes
182
+ if "article" in nodes.keys() and "article" in dgl_graph.ntypes:
183
+ if (
184
+ "title_emb" in nodes["article"].columns
185
+ and "content_emb" in nodes["article"].columns
186
+ ):
187
+ title_embs = emb_to_tensor(nodes["article"], "title_emb")
188
+ content_embs = emb_to_tensor(nodes["article"], "content_emb")
189
+ tensors = (title_embs, content_embs)
190
+ dgl_graph.nodes["article"].data["feat"] = torch.cat(tensors, dim=1)
191
+ else:
192
+ num_articles = dgl_graph.num_nodes("article")
193
+ ones = torch.ones(num_articles, 1)
194
+ dgl_graph.nodes["article"].data["feat"] = ones
195
+
196
+ # Add node features to the Image nodes
197
+ if "image" in nodes.keys() and "image" in dgl_graph.ntypes:
198
+ if "pixels_emb" in nodes["image"].columns:
199
+ image_embs = emb_to_tensor(nodes["image"], "pixels_emb")
200
+ dgl_graph.nodes["image"].data["feat"] = image_embs
201
+ else:
202
+ num_images = dgl_graph.num_nodes("image")
203
+ dgl_graph.nodes["image"].data["feat"] = torch.ones(num_images, 1)
204
+
205
+ # Add node features to the Hashtag nodes
206
+ if "hashtag" in nodes.keys() and "hashtag" in dgl_graph.ntypes:
207
+ num_hashtags = dgl_graph.num_nodes("hashtag")
208
+ dgl_graph.nodes["hashtag"].data["feat"] = torch.ones(num_hashtags, 1)
209
+
210
+ # Add node features to the Claim nodes
211
+ if "claim" in nodes.keys() and "claim" in dgl_graph.ntypes:
212
+ claim_embs = emb_to_tensor(nodes["claim"], "embedding")
213
+ if "reviewer_emb" in nodes["claim"].columns:
214
+ rev_embs = emb_to_tensor(nodes["claim"], "reviewer_emb")
215
+ tensors = (claim_embs, rev_embs)
216
+ dgl_graph.nodes["claim"].data["feat"] = torch.cat(tensors, dim=1)
217
+ else:
218
+ dgl_graph.nodes["claim"].data["feat"] = claim_embs
219
+
220
+ # Add labels
221
+ def numericalise_labels(label: str) -> int:
222
+ numericalise = dict(misinformation=0, factual=1)
223
+ return numericalise[label]
224
+
225
+ claim_labels = nodes["claim"][["label"]].applymap(numericalise_labels)
226
+ discusses = relations[("tweet", "discusses", "claim")]
227
+ tweet_labels = allowed_tweet_df.merge(
228
+ discusses.merge(claim_labels, left_on="tgt", right_index=True).drop_duplicates(
229
+ "src"
230
+ ),
231
+ left_index=True,
232
+ right_on="src",
233
+ how="left",
234
+ )
235
+ claim_label_tensor = torch.from_numpy(claim_labels.label.to_numpy())
236
+ claim_label_tensor = torch.nan_to_num(claim_label_tensor).long()
237
+ tweet_label_tensor = torch.from_numpy(tweet_labels.label.to_numpy())
238
+ tweet_label_tensor = torch.nan_to_num(tweet_label_tensor).long()
239
+ dgl_graph.nodes["claim"].data["label"] = claim_label_tensor
240
+ dgl_graph.nodes["tweet"].data["label"] = tweet_label_tensor
241
+
242
+ # Add masks
243
+ mask_names = ["train_mask", "val_mask", "test_mask"]
244
+ claim_masks = nodes["claim"][mask_names].copy()
245
+ merged = allowed_tweet_df.merge(
246
+ discusses.merge(claim_masks, left_on="tgt", right_index=True).drop_duplicates(
247
+ "src"
248
+ ),
249
+ left_index=True,
250
+ right_on="src",
251
+ how="left",
252
+ )
253
+ for col_name in mask_names:
254
+ claim_tensor = torch.from_numpy(
255
+ nodes["claim"][col_name].astype(float).to_numpy()
256
+ )
257
+ claim_tensor = torch.nan_to_num(claim_tensor).bool()
258
+ tweet_tensor = torch.from_numpy(merged[col_name].astype(float).to_numpy())
259
+ tweet_tensor = torch.nan_to_num(tweet_tensor).bool()
260
+ dgl_graph.nodes["claim"].data[col_name] = claim_tensor
261
+ dgl_graph.nodes["tweet"].data[col_name] = tweet_tensor
262
+
263
+ # Return DGL graph
264
+ return dgl_graph
265
+
266
+
267
+ def save_dgl_graph(dgl_graph, path: Union[str, Path] = "mumin.dgl"):
268
+ """Save a MuMiN DGL graph.
269
+
270
+ Args:
271
+ dgl_graph (DGL heterogeneous graph):
272
+ The graph to store.
273
+ path (str, optional):
274
+ Where to store the graph. Defaults to 'mumin.dgl'.
275
+ """
276
+ # Import the needed libraries, and raise an error if they have not yet been
277
+ # installed
278
+ try:
279
+ import torch
280
+ from dgl.data.utils import save_graphs
281
+ except ModuleNotFoundError:
282
+ raise ModuleNotFoundError(
283
+ "Could not find the `dgl` library. Please install it and try again."
284
+ )
285
+
286
+ # Convert masks to unsigned 8-bit integers
287
+ for mask_name in ["train_mask", "val_mask", "test_mask"]:
288
+ for node_type in ["claim", "tweet"]:
289
+ t = dgl_graph.nodes[node_type].data[mask_name]
290
+ dgl_graph.nodes[node_type].data[mask_name] = t.type(torch.uint8)
291
+
292
+ # Save the graph
293
+ save_graphs(str(path), [dgl_graph])
294
+
295
+
296
+ def load_dgl_graph(path: Union[str, Path] = "mumin.dgl"):
297
+ """Load a MuMiN DGL graph.
298
+
299
+ Args:
300
+ path (str or Path, optional):
301
+ Where to load the graph from. Defaults to 'mumin.dgl'.
302
+
303
+ Returns:
304
+ DGLHeteroGraph:
305
+ The MuMiN graph.
306
+ """
307
+ # Import the needed libraries, and raise an error if they have not yet been
308
+ # installed
309
+ try:
310
+ from dgl.data.utils import load_graphs
311
+ except ModuleNotFoundError:
312
+ raise ModuleNotFoundError(
313
+ "Could not find the `dgl` library. Please install it and try again."
314
+ )
315
+
316
+ # Load the graph
317
+ dgl_graph = load_graphs(str(path))[0][0]
318
+
319
+ # Convert masks back to booleans
320
+ for mask_name in ["train_mask", "val_mask", "test_mask"]:
321
+ for node_type in ["claim", "tweet"]:
322
+ mask_tensor = dgl_graph.nodes[node_type].data[mask_name]
323
+ dgl_graph.nodes[node_type].data[mask_name] = mask_tensor.bool()
324
+
325
+ # Return the graph
326
+ return dgl_graph
src/mumin/embedder.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute node embeddings for the dataset"""
2
+
3
+ import json
4
+ import warnings
5
+ from functools import partial
6
+ from typing import Dict, List, Tuple, Union
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+ from transformers import (
12
+ AutoFeatureExtractor,
13
+ AutoModel,
14
+ AutoModelForImageClassification,
15
+ AutoTokenizer,
16
+ )
17
+ from transformers import logging as tf_logging
18
+
19
+ tf_logging.set_verbosity_error()
20
+
21
+
22
+ class Embedder:
23
+ """Compute node embeddings for the dataset"""
24
+
25
+ def __init__(
26
+ self,
27
+ include_articles: bool,
28
+ include_tweet_images: bool,
29
+ include_extra_images: bool,
30
+ text_embedding_model_id: str,
31
+ image_embedding_model_id: str,
32
+ ):
33
+ self.include_articles = include_articles
34
+ self.include_tweet_images = include_tweet_images
35
+ self.include_extra_images = include_extra_images
36
+ self.text_embedding_model_id = text_embedding_model_id
37
+ self.image_embedding_model_id = image_embedding_model_id
38
+
39
+ def embed_all(
40
+ self, nodes: Dict[str, pd.DataFrame], nodes_to_embed: List[str]
41
+ ) -> Tuple[Dict[str, pd.DataFrame], bool]:
42
+ """Computes embeddings of node features.
43
+
44
+ Args:
45
+ nodes (Dict[str, pd.DataFrame]):
46
+ A dictionary of node dataframes.
47
+ nodes_to_embed (list of str):
48
+ The node types which needs to be embedded. If a node type does not
49
+ exist in the graph it will be ignored.
50
+
51
+ Returns:
52
+ pair of Dict[str, pd.DataFrame] and bool:
53
+ A dictionary of node dataframes with embeddings, and a boolean
54
+ indicating whether any embeddings were added.
55
+ """
56
+ # Create variable keeping track of whether any embeddings have been
57
+ # added
58
+ embeddings_added = False
59
+
60
+ # Embed tweets
61
+ if (
62
+ "tweet" in nodes_to_embed
63
+ and "tweet" in nodes
64
+ and len(nodes["tweet"]) > 0
65
+ and "text_emb" not in nodes["tweet"].columns
66
+ ):
67
+ nodes["tweet"] = self._embed_tweets(tweet_df=nodes["tweet"])
68
+ embeddings_added = True
69
+
70
+ # Embed replies
71
+ if (
72
+ "reply" in nodes_to_embed
73
+ and "reply" in nodes
74
+ and len(nodes["reply"]) > 0
75
+ and "text_emb" not in nodes["reply"].columns
76
+ ):
77
+ nodes["reply"] = self._embed_replies(reply_df=nodes["reply"])
78
+ embeddings_added = True
79
+
80
+ # Embed users
81
+ if (
82
+ "user" in nodes_to_embed
83
+ and "user" in nodes
84
+ and len(nodes["user"]) > 0
85
+ and "description_emb" not in nodes["user"].columns
86
+ ):
87
+ nodes["user"] = self._embed_users(user_df=nodes["user"])
88
+ embeddings_added = True
89
+
90
+ # Embed articles
91
+ if (
92
+ "article" in nodes_to_embed
93
+ and "article" in nodes
94
+ and len(nodes["article"]) > 0
95
+ and "content_emb" not in nodes["article"].columns
96
+ ):
97
+ nodes["article"] = self._embed_articles(article_df=nodes["article"])
98
+ embeddings_added = True
99
+
100
+ # Embed images
101
+ if (
102
+ "image" in nodes_to_embed
103
+ and "image" in nodes
104
+ and len(nodes["image"]) > 0
105
+ and "pixels_emb" not in nodes["image"].columns
106
+ ):
107
+ nodes["image"] = self._embed_images(image_df=nodes["image"])
108
+ embeddings_added = True
109
+
110
+ # Embed claims
111
+ if (
112
+ "claim" in nodes_to_embed
113
+ and "claim" in nodes
114
+ and len(nodes["claim"]) > 0
115
+ and "reviewer_emb" not in nodes["claim"].columns
116
+ ):
117
+ nodes["claim"] = self._embed_claims(claim_df=nodes["claim"])
118
+ embeddings_added = True
119
+
120
+ return nodes, embeddings_added
121
+
122
+ @staticmethod
123
+ def _embed_text(text: str, tokenizer, model) -> np.ndarray:
124
+ """Extract a text embedding.
125
+
126
+ Args:
127
+ text (str):
128
+ The text to embed.
129
+ tokenizer (transformers.PreTrainedTokenizer):
130
+ The tokenizer to use.
131
+ model (transformers.PreTrainedModel):
132
+ The model to use.
133
+
134
+ Returns:
135
+ np.ndarray:
136
+ The embedding of the text.
137
+ """
138
+ with torch.no_grad():
139
+ inputs = tokenizer(text, truncation=True, return_tensors="pt")
140
+ if torch.cuda.is_available():
141
+ inputs = {k: v.cuda() for k, v in inputs.items()}
142
+ result = model(**inputs)
143
+ return result.pooler_output[0].cpu().numpy()
144
+
145
+ def _embed_tweets(self, tweet_df: pd.DataFrame) -> pd.DataFrame:
146
+ """Embeds all the tweets in the dataset.
147
+
148
+ Args:
149
+ tweet_df (pd.DataFrame):
150
+ The tweet dataframe.
151
+
152
+ Returns:
153
+ pd.DataFrame:
154
+ The tweet dataframe with embeddings.
155
+ """
156
+ # Load text embedding model
157
+ model_id = self.text_embedding_model_id
158
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
159
+ model = AutoModel.from_pretrained(model_id)
160
+
161
+ # Move model to GPU if available
162
+ if torch.cuda.is_available():
163
+ model.cuda()
164
+
165
+ # Define embedding function
166
+ embed = partial(self._embed_text, tokenizer=tokenizer, model=model)
167
+
168
+ # Embed tweet text using the pretrained transformer
169
+ text_embs = tweet_df.text.progress_apply(embed)
170
+ tweet_df["text_emb"] = text_embs
171
+
172
+ # Embed tweet language using a one-hot encoding
173
+ languages = tweet_df.lang.tolist()
174
+ one_hotted = [
175
+ np.asarray(lst) for lst in pd.get_dummies(languages).to_numpy().tolist()
176
+ ]
177
+ tweet_df["lang_emb"] = one_hotted
178
+
179
+ return tweet_df
180
+
181
+ def _embed_replies(self, reply_df: pd.DataFrame) -> pd.DataFrame:
182
+ """Embeds all the replies in the dataset.
183
+
184
+ Args:
185
+ reply_df (pd.DataFrame): The reply dataframe.
186
+
187
+ Returns:
188
+ pd.DataFrame: The reply dataframe with embeddings.
189
+ """
190
+ # Load text embedding model
191
+ model_id = self.text_embedding_model_id
192
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
193
+ model = AutoModel.from_pretrained(model_id)
194
+
195
+ # Move model to GPU if available
196
+ if torch.cuda.is_available():
197
+ model.cuda()
198
+
199
+ # Define embedding function
200
+ embed = partial(self._embed_text, tokenizer=tokenizer, model=model)
201
+
202
+ # Embed tweet text using the pretrained transformer
203
+ text_embs = reply_df.text.progress_apply(embed)
204
+ reply_df["text_emb"] = text_embs
205
+
206
+ # Embed tweet language using a one-hot encoding
207
+ languages = reply_df.lang.tolist()
208
+ one_hotted = [
209
+ np.asarray(lst) for lst in pd.get_dummies(languages).to_numpy().tolist()
210
+ ]
211
+ reply_df["lang_emb"] = one_hotted
212
+
213
+ return reply_df
214
+
215
+ def _embed_users(self, user_df: pd.DataFrame) -> pd.DataFrame:
216
+ """Embeds all the users in the dataset.
217
+
218
+ Args:
219
+ user_df (pd.DataFrame):
220
+ The user dataframe.
221
+
222
+ Returns:
223
+ pd.DataFrame:
224
+ The user dataframe with embeddings.
225
+ """
226
+ # Load text embedding model
227
+ model_id = self.text_embedding_model_id
228
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
229
+ model = AutoModel.from_pretrained(model_id)
230
+
231
+ # Move model to GPU if available
232
+ if torch.cuda.is_available():
233
+ model.cuda()
234
+
235
+ # Define embedding function
236
+ def embed(text: str):
237
+ """Extract a text embedding"""
238
+ if text != text:
239
+ return np.zeros(model.config.hidden_size)
240
+ else:
241
+ return self._embed_text(text, tokenizer=tokenizer, model=model)
242
+
243
+ # Embed user description using the pretrained transformer
244
+ desc_embs = user_df.description.progress_apply(embed)
245
+ user_df["description_emb"] = desc_embs
246
+
247
+ return user_df
248
+
249
+ def _embed_articles(self, article_df: pd.DataFrame) -> pd.DataFrame:
250
+ """Embeds all the tweets in the dataset.
251
+
252
+ Args:
253
+ article_df (pd.DataFrame):
254
+ The article dataframe.
255
+
256
+ Returns:
257
+ pd.DataFrame:
258
+ The article dataframe with embeddings.
259
+ """
260
+ if self.include_articles:
261
+ # Load text embedding model
262
+ model_id = self.text_embedding_model_id
263
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
264
+ model = AutoModel.from_pretrained(model_id)
265
+
266
+ # Move model to GPU if available
267
+ if torch.cuda.is_available():
268
+ model.cuda()
269
+
270
+ # Define embedding function
271
+ def embed(text: Union[str, List[str]]):
272
+ """Extract a text embedding"""
273
+ params = dict(tokenizer=tokenizer, model=model)
274
+ if isinstance(text, str):
275
+ return self._embed_text(text, **params)
276
+ else:
277
+ return np.mean(
278
+ [self._embed_text(doc, **params) for doc in text], axis=0
279
+ )
280
+
281
+ def split_content(doc: str) -> List[str]:
282
+ """Split up a string into smaller chunks"""
283
+ if "." in doc:
284
+ return doc.split(".")
285
+ else:
286
+ end = min(len(doc) - 1000, 0)
287
+ return [doc[i : i + 1000] for i in range(0, end, 1000)] + [
288
+ doc[end:-1]
289
+ ]
290
+
291
+ # Embed titles using the pretrained transformer
292
+ title_embs = article_df.title.progress_apply(embed)
293
+ article_df["title_emb"] = title_embs
294
+
295
+ # Embed contents using the pretrained transformer
296
+ contents = article_df.content
297
+ content_embs = contents.map(split_content).progress_apply(embed)
298
+ article_df["content_emb"] = content_embs
299
+
300
+ return article_df
301
+
302
+ def _embed_images(self, image_df: pd.DataFrame) -> pd.DataFrame:
303
+ """Embeds all the images in the dataset.
304
+
305
+ Args:
306
+ image_df (pd.DataFrame):
307
+ The image dataframe.
308
+
309
+ Returns:
310
+ pd.DataFrame:
311
+ The image dataframe with embeddings.
312
+ """
313
+ if self.include_tweet_images or self.include_extra_images:
314
+ # Load image embedding model
315
+ model_id = self.image_embedding_model_id
316
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
317
+ model = AutoModelForImageClassification.from_pretrained(model_id)
318
+
319
+ # Move model to GPU if available
320
+ if torch.cuda.is_available():
321
+ model.cuda()
322
+
323
+ # Define embedding function
324
+ def embed(image):
325
+ """Extract the last hiden state of image model"""
326
+ with torch.no_grad():
327
+
328
+ # Ensure that the input has shape (C, H, W)
329
+ image = np.transpose(image, (2, 0, 1))
330
+
331
+ # Extract the features to be used in the model
332
+ inputs = feature_extractor(images=image, return_tensors="pt")
333
+
334
+ if torch.cuda.is_available():
335
+ inputs = {k: v.cuda() for k, v in inputs.items()}
336
+
337
+ # Get the embedding
338
+ outputs = model(**inputs, output_hidden_states=True)
339
+ penultimate_embedding = outputs.hidden_states[-1]
340
+ cls_embedding = penultimate_embedding[0, 0, :]
341
+
342
+ # Convert to NumPy and return
343
+ return cls_embedding.cpu().numpy()
344
+
345
+ # Embed pixels using the pretrained transformer
346
+ with warnings.catch_warnings():
347
+ warnings.simplefilter("ignore")
348
+ image_df["pixels_emb"] = image_df.pixels.progress_apply(embed).tolist()
349
+
350
+ return image_df
351
+
352
+ def _embed_claims(self, claim_df: pd.DataFrame) -> pd.DataFrame:
353
+ """Embeds all the claims in the dataset.
354
+
355
+ Args:
356
+ claim_df (pd.DataFrame):
357
+ The claim dataframe.
358
+
359
+ Returns:
360
+ pd.DataFrame:
361
+ The claim dataframe with embeddings.
362
+ """
363
+ # Ensure that `reviewers` is a list
364
+ if isinstance(claim_df.reviewers.iloc[0], str):
365
+
366
+ def string_to_list(string: str) -> list:
367
+ """Convert a string to a list.
368
+
369
+ Args:
370
+ string: A string to be converted to a list.
371
+
372
+ Returns:
373
+ list: A list of strings.
374
+ """
375
+ string = string.replace("'", '"')
376
+ return json.loads(string)
377
+
378
+ claim_df["reviewers"] = claim_df.reviewers.map(string_to_list)
379
+
380
+ # Set up one-hot encoding of claim reviewers
381
+ reviewers = claim_df.reviewers.explode().unique().tolist()
382
+ one_hotted = [
383
+ np.asarray(lst) for lst in pd.get_dummies(reviewers).to_numpy().tolist()
384
+ ]
385
+ one_hot_dict = {
386
+ reviewer: array for reviewer, array in zip(reviewers, one_hotted)
387
+ }
388
+
389
+ def embed_reviewers(revs: List[str]) -> np.ndarray:
390
+ """One-hot encoding of multiple reviewers.
391
+
392
+ Args:
393
+ revs: A list of reviewers.
394
+
395
+ Returns:
396
+ np.ndarray: A one-hot encoded array.
397
+ """
398
+ arrays = [one_hot_dict[rev] for rev in revs]
399
+ return np.stack(arrays, axis=0).sum(axis=0)
400
+
401
+ # Embed claim reviewer using a one-hot encoding
402
+ reviewer_emb = claim_df.reviewers.map(embed_reviewers)
403
+ claim_df["reviewer_emb"] = reviewer_emb
404
+
405
+ return claim_df
src/mumin/id_updator.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Class that updates the precomputed IDs"""
2
+
3
+ from typing import Dict, Tuple
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+
9
+ class IdUpdator:
10
+ """Class that updates the IDs of nodes and relations"""
11
+
12
+ def update_all(
13
+ self,
14
+ nodes: Dict[str, pd.DataFrame],
15
+ rels: Dict[Tuple[str, str, str], pd.DataFrame],
16
+ ) -> Tuple[dict, dict]:
17
+ """Extract all node and relation data.
18
+
19
+ Args:
20
+ nodes (Dict[str, pd.DataFrame]):
21
+ A dictionary of node dataframes.
22
+ rels (Dict[Tuple[str, str, str], pd.DataFrame]):
23
+ A dictionary of relation dataframes.
24
+
25
+ Returns:
26
+ pair of dicts:
27
+ A tuple of updated node and relation dictionaries.
28
+ """
29
+ rel = ("tweet", "discusses", "claim")
30
+ if rel in rels.keys():
31
+ rels[rel] = self._update_tweet_discusses_claim(
32
+ rel_df=rels[rel], tweet_df=nodes["tweet"], claim_df=nodes["claim"]
33
+ )
34
+
35
+ rel = ("article", "discusses", "claim")
36
+ if rel in rels.keys():
37
+ rels[rel] = self._update_article_discusses_claim(
38
+ rel_df=rels[rel], article_df=nodes["article"], claim_df=nodes["claim"]
39
+ )
40
+
41
+ rel = ("user", "follows", "user")
42
+ if rel in rels.keys():
43
+ rels[rel] = self._update_user_follows_user(
44
+ rel_df=rels[rel], user_df=nodes["user"]
45
+ )
46
+
47
+ rel = ("reply", "reply_to", "tweet")
48
+ if rel in rels.keys():
49
+ rels[rel] = self._update_reply_reply_to_tweet(
50
+ rel_df=rels[rel], reply_df=nodes["reply"], tweet_df=nodes["tweet"]
51
+ )
52
+
53
+ rel = ("reply", "quote_of", "tweet")
54
+ if rel in rels.keys():
55
+ rels[rel] = self._update_reply_quote_of_tweet(
56
+ rel_df=rels[rel], reply_df=nodes["reply"], tweet_df=nodes["tweet"]
57
+ )
58
+
59
+ rel = ("user", "retweeted", "tweet")
60
+ if rel in rels.keys():
61
+ rels[rel] = self._update_user_retweeted_tweet(
62
+ rel_df=rels[rel], user_df=nodes["user"], tweet_df=nodes["tweet"]
63
+ )
64
+
65
+ # Remove ID columns from the claim and article dataframes
66
+ nodes["claim"] = self._remove_id_column(node_df=nodes["claim"])
67
+ if "article" in nodes.keys():
68
+ nodes["article"] = self._remove_id_column(node_df=nodes["article"])
69
+
70
+ return nodes, rels
71
+
72
+ def _update_tweet_discusses_claim(
73
+ self, rel_df: pd.DataFrame, tweet_df: pd.DataFrame, claim_df: pd.DataFrame
74
+ ) -> pd.DataFrame:
75
+ """Update the (:Tweet)-[:DISCUSSES]->(:Claim) relation.
76
+
77
+ Args:
78
+ rel_df (pd.DataFrame): The relation dataframe.
79
+ tweet_df (pd.DataFrame): The tweet dataframe.
80
+ claim_df (pd.DataFrame): The claim dataframe.
81
+
82
+ Returns:
83
+ pd.DataFrame: The updated relation dataframe.
84
+ """
85
+ if len(rel_df) > 0:
86
+ merged = (
87
+ rel_df.astype(dict(src=np.uint64, tgt=np.uint64))
88
+ .merge(
89
+ tweet_df[["tweet_id"]]
90
+ .reset_index()
91
+ .rename(columns=dict(index="tweet_idx")),
92
+ left_on="src",
93
+ right_on="tweet_id",
94
+ )
95
+ .merge(
96
+ claim_df[["id"]]
97
+ .reset_index()
98
+ .rename(columns=dict(index="claim_idx")),
99
+ left_on="tgt",
100
+ right_on="id",
101
+ )
102
+ )
103
+ if len(merged) > 0:
104
+ data_dict = dict(
105
+ src=merged.tweet_idx.tolist(), tgt=merged.claim_idx.tolist()
106
+ )
107
+ rel_df = pd.DataFrame(data_dict)
108
+ else:
109
+ rel_df = pd.DataFrame()
110
+
111
+ return rel_df
112
+
113
+ def _update_article_discusses_claim(
114
+ self, rel_df: pd.DataFrame, article_df: pd.DataFrame, claim_df: pd.DataFrame
115
+ ) -> pd.DataFrame:
116
+ """Update the (:Article)-[:DISCUSSES]->(:Claim) relation.
117
+
118
+ Args:
119
+ rel_df (pd.DataFrame): The relation dataframe.
120
+ article_df (pd.DataFrame): The article dataframe.
121
+ claim_df (pd.DataFrame): The claim dataframe.
122
+
123
+ Returns:
124
+ pd.DataFrame: The updated relation dataframe.
125
+ """
126
+ if len(rel_df) > 0:
127
+ merged = (
128
+ rel_df.astype(dict(src=np.uint64, tgt=np.uint64))
129
+ .merge(
130
+ article_df[["id"]]
131
+ .reset_index()
132
+ .rename(columns=dict(index="art_idx")),
133
+ left_on="src",
134
+ right_on="id",
135
+ )
136
+ .merge(
137
+ claim_df[["id"]]
138
+ .reset_index()
139
+ .rename(columns=dict(index="claim_idx")),
140
+ left_on="tgt",
141
+ right_on="id",
142
+ )
143
+ )
144
+ if len(merged) > 0:
145
+ data_dict = dict(
146
+ src=merged.art_idx.tolist(), tgt=merged.claim_idx.tolist()
147
+ )
148
+ rel_df = pd.DataFrame(data_dict)
149
+ else:
150
+ rel_df = pd.DataFrame()
151
+
152
+ return rel_df
153
+
154
+ def _update_user_follows_user(
155
+ self, rel_df: pd.DataFrame, user_df: pd.DataFrame
156
+ ) -> pd.DataFrame:
157
+ """Update the (:User)-[:FOLLOWS]->(:User) relation.
158
+
159
+ Args:
160
+ rel_df (pd.DataFrame): The relation dataframe.
161
+ user_df (pd.DataFrame): The user dataframe.
162
+
163
+ Returns:
164
+ pd.DataFrame: The updated relation dataframe.
165
+ """
166
+ if len(rel_df) > 0:
167
+ merged = (
168
+ rel_df.astype(dict(src=np.uint64, tgt=np.uint64))
169
+ .merge(
170
+ user_df[["user_id"]]
171
+ .reset_index()
172
+ .rename(columns=dict(index="user_idx1")),
173
+ left_on="src",
174
+ right_on="user_id",
175
+ )
176
+ .merge(
177
+ user_df[["user_id"]]
178
+ .reset_index()
179
+ .rename(columns=dict(index="user_idx2")),
180
+ left_on="tgt",
181
+ right_on="user_id",
182
+ )
183
+ )
184
+ if len(merged) > 0:
185
+ data_dict = dict(
186
+ src=merged.user_idx1.tolist(), tgt=merged.user_idx2.tolist()
187
+ )
188
+ rel_df = pd.DataFrame(data_dict)
189
+ else:
190
+ rel_df = pd.DataFrame()
191
+
192
+ return rel_df
193
+
194
+ def _update_reply_reply_to_tweet(
195
+ self, rel_df: pd.DataFrame, reply_df: pd.DataFrame, tweet_df: pd.DataFrame
196
+ ) -> pd.DataFrame:
197
+ """Update the (:Reply)-[:REPLY_TO]->(:Tweet) relation.
198
+
199
+ Args:
200
+ rel_df (pd.DataFrame): The relation dataframe.
201
+ reply_df (pd.DataFrame): The reply dataframe.
202
+ tweet_df (pd.DataFrame): The tweet dataframe.
203
+
204
+ Returns:
205
+ pd.DataFrame: The updated relation dataframe.
206
+ """
207
+ if len(rel_df) > 0:
208
+ merged = (
209
+ rel_df.astype(dict(src=np.uint64, tgt=np.uint64))
210
+ .merge(
211
+ reply_df[["tweet_id"]]
212
+ .reset_index()
213
+ .rename(columns=dict(index="reply_idx")),
214
+ left_on="src",
215
+ right_on="tweet_id",
216
+ )
217
+ .merge(
218
+ tweet_df[["tweet_id"]]
219
+ .reset_index()
220
+ .rename(columns=dict(index="tweet_idx")),
221
+ left_on="tgt",
222
+ right_on="tweet_id",
223
+ )
224
+ )
225
+ if len(merged) > 0:
226
+ data_dict = dict(
227
+ src=merged.reply_idx.tolist(), tgt=merged.tweet_idx.tolist()
228
+ )
229
+ rel_df = pd.DataFrame(data_dict)
230
+ else:
231
+ rel_df = pd.DataFrame()
232
+
233
+ return rel_df
234
+
235
+ def _update_reply_quote_of_tweet(
236
+ self, rel_df: pd.DataFrame, reply_df: pd.DataFrame, tweet_df: pd.DataFrame
237
+ ) -> pd.DataFrame:
238
+ """Update the (:Reply)-[:QUOTE_OF]->(:Tweet) relation.
239
+
240
+ Args:
241
+ rel_df (pd.DataFrame): The relation dataframe.
242
+ reply_df (pd.DataFrame): The reply dataframe.
243
+ tweet_df (pd.DataFrame): The tweet dataframe.
244
+
245
+ Returns:
246
+ pd.DataFrame: The updated relation dataframe.
247
+ """
248
+ if len(rel_df) > 0:
249
+ merged = (
250
+ rel_df.astype(dict(src=np.uint64, tgt=np.uint64))
251
+ .merge(
252
+ reply_df[["tweet_id"]]
253
+ .reset_index()
254
+ .rename(columns=dict(index="reply_idx")),
255
+ left_on="src",
256
+ right_on="tweet_id",
257
+ )
258
+ .merge(
259
+ tweet_df[["tweet_id"]]
260
+ .reset_index()
261
+ .rename(columns=dict(index="tweet_idx")),
262
+ left_on="tgt",
263
+ right_on="tweet_id",
264
+ )
265
+ )
266
+ if len(merged) > 0:
267
+ data_dict = dict(
268
+ src=merged.reply_idx.tolist(), tgt=merged.tweet_idx.tolist()
269
+ )
270
+ rel_df = pd.DataFrame(data_dict)
271
+ else:
272
+ rel_df = pd.DataFrame()
273
+
274
+ return rel_df
275
+
276
+ def _update_user_retweeted_tweet(
277
+ self, rel_df: pd.DataFrame, user_df: pd.DataFrame, tweet_df: pd.DataFrame
278
+ ) -> pd.DataFrame:
279
+ """Update the (:User)-[:RETWEETED]->(:Tweet) relation.
280
+
281
+ Args:
282
+ rel_df (pd.DataFrame): The relation dataframe.
283
+ user_df (pd.DataFrame): The user dataframe.
284
+ tweet_df (pd.DataFrame): The tweet dataframe.
285
+
286
+ Returns:
287
+ pd.DataFrame: The updated relation dataframe.
288
+ """
289
+ if len(rel_df) > 0:
290
+ merged = (
291
+ rel_df.astype(dict(src=np.uint64, tgt=np.uint64))
292
+ .merge(
293
+ user_df[["user_id"]]
294
+ .reset_index()
295
+ .rename(columns=dict(index="user_idx")),
296
+ left_on="src",
297
+ right_on="user_id",
298
+ )
299
+ .merge(
300
+ tweet_df[["tweet_id"]]
301
+ .reset_index()
302
+ .rename(columns=dict(index="tweet_idx")),
303
+ left_on="tgt",
304
+ right_on="tweet_id",
305
+ )
306
+ )
307
+ if len(merged) > 0:
308
+ data_dict = dict(
309
+ src=merged.user_idx.tolist(), tgt=merged.tweet_idx.tolist()
310
+ )
311
+ rel_df = pd.DataFrame(data_dict)
312
+ else:
313
+ rel_df = pd.DataFrame()
314
+
315
+ return rel_df
316
+
317
+ def _remove_id_column(self, node_df: pd.DataFrame) -> pd.DataFrame:
318
+ """Remove the id column from the node dataframe.
319
+
320
+ Args:
321
+ node_df (pd.DataFrame): The node dataframe.
322
+
323
+ Returns:
324
+ pd.DataFrame: The node dataframe without the id column.
325
+ """
326
+ if len(node_df) > 0:
327
+ node_df = node_df.drop(columns="id")
328
+ return node_df
src/mumin/image.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions related to processing images"""
2
+
3
+ import io
4
+ import time
5
+ import warnings
6
+ from typing import Union
7
+
8
+ import numpy as np
9
+ import requests
10
+ from PIL import Image
11
+ from wrapt_timeout_decorator.wrapt_timeout_decorator import timeout
12
+
13
+
14
+ @timeout(10)
15
+ def download_image_with_timeout(url: str) -> np.ndarray:
16
+ while True:
17
+ # Get the data from the URL, and try again if it fails
18
+ response = requests.get(url)
19
+ if response.status_code != 200:
20
+ time.sleep(1)
21
+ continue
22
+
23
+ # Convert the data to a NumPy array
24
+ byte_file = io.BytesIO(response.content)
25
+ image = np.asarray(Image.open(byte_file), dtype=np.uint8)
26
+ return image
27
+
28
+
29
+ def process_image_url(url: str) -> Union[None, dict]:
30
+ """Process the URL and extract the article.
31
+
32
+ Args:
33
+ url (str): The URL.
34
+
35
+ Returns:
36
+ dict or None:
37
+ The processed article, or None if the URL could not be parsed.
38
+ """
39
+ # Ignore warnings while processing images
40
+ with warnings.catch_warnings():
41
+ warnings.simplefilter("ignore")
42
+
43
+ try:
44
+ image = download_image_with_timeout(url)
45
+ except: # noqa
46
+ return None
47
+
48
+ if image is None:
49
+ return None
50
+ else:
51
+ try:
52
+ return dict(
53
+ url=url, pixels=image, height=image.shape[0], width=image.shape[1]
54
+ )
55
+ except IndexError:
56
+ return None
src/mumin/twitter.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper for the Twitter API"""
2
+
3
+ import logging
4
+ import time
5
+ from json import JSONDecodeError
6
+ from typing import Dict, List, Union
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import requests
11
+ from tqdm.auto import tqdm
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class Twitter:
17
+ """A wrapper for the Twitter API.
18
+
19
+ Args:
20
+ twitter_bearer_token (str):
21
+ The bearer token from the Twitter API.
22
+ """
23
+
24
+ tweet_lookup_url: str = "https://api.twitter.com/2/tweets"
25
+
26
+ def __init__(self, twitter_bearer_token: str):
27
+ self.api_key = twitter_bearer_token
28
+ self.headers = dict(Authorization=f"Bearer {self.api_key}")
29
+ self.expansions = [
30
+ "attachments.poll_ids",
31
+ "attachments.media_keys",
32
+ "author_id",
33
+ "entities.mentions.username",
34
+ "geo.place_id",
35
+ "in_reply_to_user_id",
36
+ "referenced_tweets.id",
37
+ "referenced_tweets.id.author_id",
38
+ ]
39
+ self.tweet_fields = [
40
+ "attachments",
41
+ "author_id",
42
+ "conversation_id",
43
+ "created_at",
44
+ "entities",
45
+ "geo",
46
+ "id",
47
+ "in_reply_to_user_id",
48
+ "lang",
49
+ "public_metrics",
50
+ "possibly_sensitive",
51
+ "referenced_tweets",
52
+ "reply_settings",
53
+ "source",
54
+ "text",
55
+ "withheld",
56
+ ]
57
+ self.user_fields = [
58
+ "created_at",
59
+ "description",
60
+ "entities",
61
+ "id",
62
+ "location",
63
+ "name",
64
+ "pinned_tweet_id",
65
+ "profile_image_url",
66
+ "protected",
67
+ "public_metrics",
68
+ "url",
69
+ "username",
70
+ "verified",
71
+ "withheld",
72
+ ]
73
+ self.media_fields = [
74
+ "duration_ms",
75
+ "height",
76
+ "media_key",
77
+ "preview_image_url",
78
+ "type",
79
+ "url",
80
+ "width",
81
+ "public_metrics",
82
+ ]
83
+ self.place_fields = [
84
+ "contained_within",
85
+ "country",
86
+ "country_code",
87
+ "full_name",
88
+ "geo",
89
+ "id",
90
+ "name",
91
+ "place_type",
92
+ ]
93
+ self.poll_fields = [
94
+ "duration_minutes",
95
+ "end_datetime",
96
+ "id",
97
+ "options",
98
+ "voting_status",
99
+ ]
100
+
101
+ def rehydrate_tweets(
102
+ self, tweet_ids: List[Union[str, np.uint64]]
103
+ ) -> Dict[str, pd.DataFrame]:
104
+ """Rehydrates the tweets for the given tweet IDs.
105
+
106
+ Args:
107
+ tweet_ids (list of either str or uint64):
108
+ The tweet IDs to rehydrate.
109
+
110
+ Returns:
111
+ dict:
112
+ A dictionary with keys 'tweets', 'users', 'media', 'polls' and
113
+ 'places', where the values are the associated Pandas DataFrame objects.
114
+ """
115
+ # Ensure that the tweet IDs are strings
116
+ tweet_ids = list(map(str, tweet_ids))
117
+
118
+ # Set up the params for the GET request
119
+ get_params = {
120
+ "expansions": ",".join(self.expansions),
121
+ "media.fields": ",".join(self.media_fields),
122
+ "place.fields": ",".join(self.place_fields),
123
+ "poll.fields": ",".join(self.poll_fields),
124
+ "tweet.fields": ",".join(self.tweet_fields),
125
+ "user.fields": ",".join(self.user_fields),
126
+ }
127
+
128
+ # Split `tweet_ids` into batches of at most 100, as this is the maximum number
129
+ # allowed by the API
130
+ num_batches = len(tweet_ids) // 100
131
+ if len(tweet_ids) % 100 != 0:
132
+ num_batches += 1
133
+ batches = np.array_split(tweet_ids, num_batches)
134
+
135
+ # Initialise dataframes
136
+ tweet_df = pd.DataFrame()
137
+ user_df = pd.DataFrame()
138
+ media_df = pd.DataFrame()
139
+ poll_df = pd.DataFrame()
140
+ place_df = pd.DataFrame()
141
+
142
+ # Initialise progress bar
143
+ if len(batches) > 1:
144
+ pbar = tqdm(total=len(tweet_ids), desc="Rehydrating")
145
+
146
+ # Loop over all the batches
147
+ for batch in batches:
148
+
149
+ # Add the batch tweet IDs to the batch
150
+ get_params["ids"] = ",".join(batch)
151
+
152
+ # Perform the GET request
153
+ try:
154
+ response = requests.get(
155
+ self.tweet_lookup_url, params=get_params, headers=self.headers
156
+ )
157
+ except requests.exceptions.RequestException as e:
158
+ logger.error(
159
+ f"[{e}] Error in rehydrating tweets.\nThe "
160
+ f"parameters used were {get_params}."
161
+ )
162
+ continue
163
+
164
+ # If we have reached the API limit then wait a bit and try again
165
+ while response.status_code in [429, 503]:
166
+ logger.debug("Request limit reached. Waiting...")
167
+ time.sleep(1)
168
+ try:
169
+ response = requests.get(
170
+ self.tweet_lookup_url, params=get_params, headers=self.headers
171
+ )
172
+ except requests.exceptions.RequestException as e:
173
+ logger.error(
174
+ f"[{e}] Error in rehydrating tweets.\nThe "
175
+ f"parameters used were {get_params}."
176
+ )
177
+ continue
178
+
179
+ # If we are not authorised then continue to the next batch
180
+ if response.status_code == 401:
181
+ continue
182
+
183
+ # If the GET request failed then continue to the next batch
184
+ elif response.status_code != 200:
185
+ logger.error(f"[{response.status_code}] {response.content!r}")
186
+ continue
187
+
188
+ # Convert the response to a dict
189
+ try:
190
+ data_dict = response.json()
191
+ except JSONDecodeError as e:
192
+ logger.error(
193
+ f"[{e}] Error in unpacking tweets.\nThe "
194
+ f"parameters used were {get_params}."
195
+ )
196
+ continue
197
+
198
+ # If the query returned errors then continue to the next batch
199
+ if "data" not in data_dict and "errors" in data_dict:
200
+ error = data_dict["errors"][0]
201
+ logger.error(error["detail"])
202
+ continue
203
+
204
+ # Tweet dataframe
205
+ if "data" in data_dict:
206
+ df = pd.json_normalize(data_dict["data"]).rename(
207
+ columns=dict(id="tweet_id")
208
+ )
209
+ tweet_df = (
210
+ pd.concat((tweet_df, df))
211
+ .drop_duplicates(subset="tweet_id")
212
+ .astype(dict(tweet_id=np.uint64))
213
+ .reset_index(drop=True)
214
+ )
215
+
216
+ # User dataframe
217
+ if "includes" in data_dict and "users" in data_dict["includes"]:
218
+ users = data_dict["includes"]["users"]
219
+ df = pd.json_normalize(users).rename(columns=dict(id="user_id"))
220
+ user_df = (
221
+ pd.concat((user_df, df))
222
+ .drop_duplicates(subset="user_id")
223
+ .astype(dict(user_id=np.uint64))
224
+ .reset_index(drop=True)
225
+ )
226
+
227
+ # Media dataframe
228
+ if "includes" in data_dict and "media" in data_dict["includes"]:
229
+ media = data_dict["includes"]["media"]
230
+ df = pd.json_normalize(media)
231
+ media_df = (
232
+ pd.concat((media_df, df))
233
+ .drop_duplicates(subset="media_key")
234
+ .reset_index(drop=True)
235
+ )
236
+
237
+ # Poll dataframe
238
+ if "includes" in data_dict and "polls" in data_dict["includes"]:
239
+ polls = data_dict["includes"]["polls"]
240
+ df = pd.json_normalize(polls).rename(columns=dict(id="poll_id"))
241
+ poll_df = (
242
+ pd.concat((poll_df, df))
243
+ .drop_duplicates(subset="poll_id")
244
+ .astype(dict(poll_id=np.uint64))
245
+ .reset_index(drop=True)
246
+ )
247
+
248
+ # Places dataframe
249
+ if "includes" in data_dict and "places" in data_dict["includes"]:
250
+ places = data_dict["includes"]["places"]
251
+ df = pd.json_normalize(places).rename(columns=dict(id="place_id"))
252
+ place_df = (
253
+ pd.concat((place_df, df))
254
+ .drop_duplicates(subset="place_id")
255
+ .reset_index(drop=True)
256
+ )
257
+
258
+ # Update the progress bar
259
+ if len(batches) > 1:
260
+ pbar.update(len(batch))
261
+
262
+ # Close the progress bar
263
+ if len(batches) > 1:
264
+ pbar.close()
265
+
266
+ # Collect all the resulting dataframes
267
+ all_dfs = dict(
268
+ tweets=tweet_df,
269
+ users=user_df,
270
+ media=media_df,
271
+ polls=poll_df,
272
+ places=place_df,
273
+ )
274
+
275
+ # Return the dictionary containing all the dataframes
276
+ return all_dfs
src/scripts/compile_mumin.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compilation of the MuMin datasets."""
2
+
3
+ import logging
4
+ import os
5
+ import sys
6
+
7
+ from dotenv import load_dotenv
8
+
9
+ from src.mumin import MuminDataset
10
+
11
+ load_dotenv()
12
+
13
+
14
+ def compile_mumin(size: str = "small") -> MuminDataset:
15
+ """Compile the MuMiN dataset.
16
+
17
+ Args:
18
+ size (str):
19
+ The size of the dataset to compile. Can be "small", "medium", or "large".
20
+ """
21
+ logging.info(f"Compiling {size} MuMin dataset...")
22
+ bearer_token = str(os.getenv("TWITTER_API_KEY"))
23
+ dataset = MuminDataset(twitter_bearer_token=bearer_token, size=size)
24
+ dataset.compile()
25
+ return dataset
26
+
27
+
28
+ if __name__ == "__main__":
29
+ if len(sys.argv) > 1:
30
+ dataset = compile_mumin(sys.argv[1])
31
+ else:
32
+ dataset = compile_mumin()
src/scripts/fix_dot_env_file.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks related to the .env file in the repository."""
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+ # List of all the environment variables that are desired
7
+ DESIRED_ENVIRONMENT_VARIABLES = dict(
8
+ GPG_KEY_ID="Enter GPG key ID or leave empty if you do not want to use it. Type "
9
+ "`gpg --list-secret-keys --keyid-format=long | grep sec | sed -E "
10
+ "'s/.*\/([^ ]+).*/\\1/'` to see your key ID:\n> ", # noqa
11
+ GIT_NAME="Enter your full name, to be shown in Git commits:\n> ",
12
+ GIT_EMAIL="Enter your email, as registered on your Github account:\n> ",
13
+ PYPI_API_TOKEN="Enter your PyPI API token, or leave empty if you do not want "
14
+ "to use it:\n> ",
15
+ )
16
+
17
+
18
+ def fix_dot_env_file():
19
+ """Ensures that the .env file exists and contains all desired variables."""
20
+ # Create path to the .env file
21
+ env_file_path = Path(".env")
22
+
23
+ # Ensure that the .env file exists
24
+ env_file_path.touch(exist_ok=True)
25
+
26
+ # Otherwise, extract all the lines in the .env file
27
+ env_file_lines = env_file_path.read_text().splitlines(keepends=False)
28
+
29
+ # Extract all the environment variables in the .env file
30
+ env_vars = [line.split("=")[0] for line in env_file_lines]
31
+
32
+ # For each of the desired environment variables, check if it exists in the .env
33
+ # file
34
+ env_vars_missing = [
35
+ env_var
36
+ for env_var in DESIRED_ENVIRONMENT_VARIABLES.keys()
37
+ if env_var not in env_vars
38
+ ]
39
+
40
+ # Create all the missing environment variables
41
+ with env_file_path.open("a") as f:
42
+ for env_var in env_vars_missing:
43
+ value = ""
44
+ if env_var == "GPG_KEY_ID":
45
+ gpg = subprocess.Popen(
46
+ ["gpg", "--list-secret-keys", "--keyid-format=long"],
47
+ stdout=subprocess.PIPE,
48
+ )
49
+ grep = subprocess.Popen(
50
+ ["grep", "sec"], stdin=gpg.stdout, stdout=subprocess.PIPE
51
+ )
52
+ value = (
53
+ subprocess.check_output(
54
+ ["sed", "-E", "s/.*\\/([^ ]+).*/\\1/"],
55
+ stdin=grep.stdout,
56
+ )
57
+ .decode()
58
+ .strip("\n")
59
+ )
60
+ gpg.wait()
61
+ grep.wait()
62
+ if value == "":
63
+ value = input(DESIRED_ENVIRONMENT_VARIABLES[env_var])
64
+ f.write(f'{env_var}="{value}"\n')
65
+
66
+
67
+ if __name__ == "__main__":
68
+ fix_dot_env_file()
src/scripts/versioning.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scripts related to updating of version."""
2
+
3
+ import datetime as dt
4
+ import re
5
+ import subprocess
6
+ from pathlib import Path
7
+ from typing import Tuple
8
+
9
+
10
+ def bump_major():
11
+ """Add one to the major version."""
12
+ major, _, _ = get_current_version()
13
+ set_new_version(major + 1, 0, 0)
14
+
15
+
16
+ def bump_minor():
17
+ """Add one to the minor version."""
18
+ major, minor, _ = get_current_version()
19
+ set_new_version(major, minor + 1, 0)
20
+
21
+
22
+ def bump_patch():
23
+ """Add one to the patch version."""
24
+ major, minor, patch = get_current_version()
25
+ set_new_version(major, minor, patch + 1)
26
+
27
+
28
+ def set_new_version(major: int, minor: int, patch: int):
29
+ """Sets a new version.
30
+
31
+ Args:
32
+ major (int):
33
+ The major version. This only changes when the code stops being backwards
34
+ compatible.
35
+ minor (int):
36
+ The minor version. This changes when a backwards compatible change
37
+ happened.
38
+ patch (init):
39
+ The patch version. This changes when the only new changes are bug fixes.
40
+ """
41
+ version = f"{major}.{minor}.{patch}"
42
+
43
+ # Get current changelog and ensure that it has an [Unreleased] entry
44
+ changelog_path = Path("CHANGELOG.md")
45
+ changelog = changelog_path.read_text()
46
+ if "[Unreleased]" not in changelog:
47
+ raise RuntimeError("No [Unreleased] entry in CHANGELOG.md.")
48
+
49
+ # Add version to CHANGELOG
50
+ today = dt.date.today().strftime("%Y-%m-%d")
51
+ new_changelog = re.sub(r"\[Unreleased\].*", f"[v{version}] - {today}", changelog)
52
+ changelog_path.write_text(new_changelog)
53
+
54
+ # Update the version in the `pyproject.toml` file
55
+ pyproject_path = Path("pyproject.toml")
56
+ pyproject = pyproject_path.read_text()
57
+ pyproject = re.sub(
58
+ r'version = "[^"]+"',
59
+ f'version = "{version}"',
60
+ pyproject,
61
+ count=1,
62
+ )
63
+ pyproject_path.write_text(pyproject)
64
+
65
+ # Add to version control
66
+ subprocess.run(["git", "add", "CHANGELOG.md"])
67
+ subprocess.run(["git", "add", "pyproject.toml"])
68
+ subprocess.run(["git", "commit", "-m", f"feat: v{version}"])
69
+ subprocess.run(["git", "tag", f"v{version}"])
70
+ subprocess.run(["git", "push"])
71
+ subprocess.run(["git", "push", "--tags"])
72
+
73
+
74
+ def get_current_version() -> Tuple[int, int, int]:
75
+ """Fetch the current version of the package.
76
+
77
+ Returns:
78
+ triple of ints:
79
+ The current version, separated into major, minor and patch versions.
80
+ """
81
+ # Get all the version candidates from pyproject.toml
82
+ version_candidates = re.search(
83
+ r'(?<=version = ")[^"]+(?=")', Path("pyproject.toml").read_text()
84
+ )
85
+
86
+ # If no version candidates were found, raise an error
87
+ if version_candidates is None:
88
+ raise RuntimeError("No version found in pyproject.toml.")
89
+
90
+ # Otherwise, extract the version, split it into major, minor and patch parts and
91
+ # return these
92
+ else:
93
+ version_str = version_candidates.group(0)
94
+ major, minor, patch = map(int, version_str.split("."))
95
+ return major, minor, patch
96
+
97
+
98
+ if __name__ == "__main__":
99
+ from argparse import ArgumentParser
100
+
101
+ parser = ArgumentParser()
102
+ parser.add_argument(
103
+ "--major",
104
+ const=True,
105
+ nargs="?",
106
+ default=False,
107
+ help="Bump the major version by one.",
108
+ )
109
+ parser.add_argument(
110
+ "--minor",
111
+ const=True,
112
+ nargs="?",
113
+ default=False,
114
+ help="Bump the minor version by one.",
115
+ )
116
+ parser.add_argument(
117
+ "--patch",
118
+ const=True,
119
+ nargs="?",
120
+ default=False,
121
+ help="Bump the patch version by one.",
122
+ )
123
+ args = parser.parse_args()
124
+
125
+ if args.major + args.minor + args.patch != 1:
126
+ raise RuntimeError(
127
+ "Exactly one of --major, --minor and --patch must be selected."
128
+ )
129
+ elif args.major:
130
+ bump_major()
131
+ elif args.minor:
132
+ bump_minor()
133
+ elif args.patch:
134
+ bump_patch()
tests/.gitkeep ADDED
File without changes
tests/test_article.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the `article` module."""
2
+
3
+ import pytest
4
+ from newspaper import Article
5
+
6
+ from mumin.article import download_article_with_timeout, process_article_url
7
+
8
+ WORKING_URL: str = "https://www.bbc.com/news/62261164"
9
+ BAD_GATEWAY_URL: str = (
10
+ "https://www.diariodocentrodomundo.com.br/finlandia-tera-jornada-"
11
+ "de-trabalho-de-seis-horas-quatro-dias-por-semana"
12
+ )
13
+ BIG_FILE_URL: str = (
14
+ "https://filedn.com/lRBwPhPxgV74tO0rDoe8SpH/scholarly_data/arxiv_data.db"
15
+ )
16
+
17
+
18
+ @pytest.mark.parametrize(
19
+ argnames="url, has_html",
20
+ argvalues=[
21
+ (WORKING_URL, True),
22
+ (BAD_GATEWAY_URL, True),
23
+ (BIG_FILE_URL, False),
24
+ ],
25
+ ids=["working_url", "bad_gateway_url", "big_file_url"],
26
+ )
27
+ def test_download_article(url, has_html):
28
+ article = Article(url)
29
+ assert article.html == ""
30
+ article = download_article_with_timeout(article)
31
+ assert isinstance(article, Article)
32
+ if has_html:
33
+ assert article.html != ""
34
+ else:
35
+ assert article.html == ""
36
+
37
+
38
+ def test_process_article_url_bad_url():
39
+ assert process_article_url(BIG_FILE_URL) is None
40
+
41
+
42
+ @pytest.mark.parametrize(
43
+ argnames="article_config",
44
+ argvalues=[
45
+ dict(
46
+ url=WORKING_URL,
47
+ title="Capitol riot: Trump ignored pleas to condemn attack, hearing told",
48
+ authors=[],
49
+ publish_date=None,
50
+ top_image_url="https://ichef.bbci.co.uk/news/1024/branded_news/11A62/"
51
+ "production/_126009227_capitol_riot_2_getty.jpg",
52
+ ),
53
+ dict(
54
+ url=BAD_GATEWAY_URL,
55
+ title="Finlândia terá jornada de trabalho de seis horas, quatro "
56
+ "dias por semana",
57
+ authors=["Diario Do Centro Do Mundo", "Publicado Por"],
58
+ publish_date="2020-01-06",
59
+ top_image_url="https://www.diariodocentrodomundo.com.br/wp-content/"
60
+ "uploads/2019/12/premie.jpg",
61
+ ),
62
+ ],
63
+ ids=[
64
+ "working_url",
65
+ "bad_gateway_url",
66
+ ],
67
+ scope="class",
68
+ )
69
+ class TestProcessArticleUrl:
70
+ @pytest.fixture(scope="class")
71
+ def processed_article(self, article_config):
72
+ yield process_article_url(article_config["url"])
73
+
74
+ def test_is_dict(self, processed_article, article_config):
75
+ assert isinstance(processed_article, dict)
76
+
77
+ def test_url(self, processed_article, article_config):
78
+ assert processed_article["url"] == article_config["url"]
79
+
80
+ def test_title(self, processed_article, article_config):
81
+ assert processed_article["title"] == article_config["title"]
82
+
83
+ def test_authors(self, processed_article, article_config):
84
+ assert processed_article["authors"] == article_config["authors"]
85
+
86
+ def test_publish_date(self, processed_article, article_config):
87
+ assert processed_article["publish_date"] == article_config["publish_date"]
88
+
89
+ def test_top_image_url(self, processed_article, article_config):
90
+ assert processed_article["top_image_url"] == article_config["top_image_url"]
tests/test_data_extractor.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Unit tests for the `data_extractor` module."""
tests/test_dataset.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the `dataset` module."""
2
+
3
+ import os
4
+ import warnings
5
+ from copy import deepcopy
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ from dotenv import load_dotenv
10
+
11
+ from mumin import MuminDataset, load_dgl_graph, save_dgl_graph
12
+
13
+ load_dotenv()
14
+
15
+
16
+ class TestMuminDataset:
17
+ @pytest.fixture(scope="class")
18
+ def dataset(self):
19
+ yield MuminDataset(str(os.getenv("TWITTER_API_KEY")), size="test", verbose=True)
20
+
21
+ @pytest.fixture(scope="class")
22
+ def compiled_dataset(self, dataset):
23
+ yield dataset.compile(overwrite=True)
24
+
25
+ @pytest.fixture(scope="class")
26
+ def dataset_with_embeddings(self, compiled_dataset):
27
+ with warnings.catch_warnings():
28
+ warnings.simplefilter("ignore", category=DeprecationWarning)
29
+ copied_dataset = deepcopy(compiled_dataset)
30
+ copied_dataset.add_embeddings()
31
+ yield copied_dataset
32
+
33
+ @pytest.fixture(scope="class")
34
+ def dgl_graph(self, compiled_dataset):
35
+ yield compiled_dataset.to_dgl()
36
+
37
+ @pytest.fixture(scope="class")
38
+ def dgl_graph_path(self):
39
+ yield Path("data/mumin-test.dgl")
40
+
41
+ def test_nodes_and_rels_are_empty_dicts(self, dataset):
42
+ assert dataset.nodes == dict()
43
+ assert dataset.rels == dict()
44
+
45
+ def test_initialize_dataset_without_bearer_token(self, dataset):
46
+ new_dataset = MuminDataset(size="test")
47
+ assert dataset._twitter.api_key == new_dataset._twitter.api_key
48
+
49
+ @pytest.mark.parametrize(
50
+ argnames="node_type",
51
+ argvalues=["claim", "tweet", "reply", "user", "article", "image", "hashtag"],
52
+ ids=["claim", "tweet", "reply", "user", "article", "image", "hashtag"],
53
+ )
54
+ def test_compiled_dataset_contains_node_type(self, compiled_dataset, node_type):
55
+ assert node_type in compiled_dataset.nodes.keys()
56
+ assert len(compiled_dataset.nodes[node_type]) > 0
57
+
58
+ @pytest.mark.parametrize(
59
+ argnames="rel_type",
60
+ argvalues=[
61
+ ("tweet", "discusses", "claim"),
62
+ ("tweet", "has_hashtag", "hashtag"),
63
+ ("tweet", "has_article", "article"),
64
+ ("reply", "reply_to", "tweet"),
65
+ ("reply", "quote_of", "tweet"),
66
+ ("user", "posted", "tweet"),
67
+ ("user", "posted", "reply"),
68
+ ("user", "mentions", "user"),
69
+ ("tweet", "has_image", "image"),
70
+ ],
71
+ ids=[
72
+ "tweet_discusses_claim",
73
+ "tweet_has_hashtag_hashtag",
74
+ "tweet_has_article_article",
75
+ "reply_reply_to_tweet",
76
+ "reply_quote_of_tweet",
77
+ "user_posted_tweet",
78
+ "user_posted_reply",
79
+ "user_mentions_user",
80
+ "tweet_has_image_image",
81
+ ],
82
+ )
83
+ def test_compiled_dataset_contains_rel_type(self, compiled_dataset, rel_type):
84
+ assert rel_type in compiled_dataset.rels.keys()
85
+ assert len(compiled_dataset.rels[rel_type]) > 0
86
+
87
+ @pytest.mark.skip(reason="DGL not available")
88
+ def test_to_dgl(self, dgl_graph):
89
+ from dgl import DGLHeteroGraph
90
+
91
+ assert isinstance(dgl_graph, DGLHeteroGraph)
92
+
93
+ @pytest.mark.skip(reason="DGL not available")
94
+ def test_save_dgl(self, dgl_graph, dgl_graph_path):
95
+ if dgl_graph_path.exists():
96
+ dgl_graph_path.unlink()
97
+ save_dgl_graph(dgl_graph, dgl_graph_path)
98
+ assert dgl_graph_path.exists()
99
+
100
+ @pytest.mark.skip(reason="DGL not available")
101
+ def test_load_dgl(self, dgl_graph_path):
102
+ from dgl import DGLHeteroGraph
103
+
104
+ if dgl_graph_path.exists():
105
+ dgl_graph = load_dgl_graph(dgl_graph_path)
106
+ assert isinstance(dgl_graph, DGLHeteroGraph)
107
+ dgl_graph_path.unlink()
108
+
109
+ @pytest.mark.parametrize(
110
+ argnames="node_type, embedding_name",
111
+ argvalues=[
112
+ ("tweet", "text_emb"),
113
+ ("reply", "text_emb"),
114
+ ("user", "description_emb"),
115
+ ("article", "content_emb"),
116
+ ("image", "pixels_emb"),
117
+ ("claim", "reviewer_emb"),
118
+ ],
119
+ ids=[
120
+ "tweet",
121
+ "reply",
122
+ "user",
123
+ "article",
124
+ "image",
125
+ "claim",
126
+ ],
127
+ )
128
+ def test_embed(self, dataset_with_embeddings, node_type, embedding_name):
129
+ assert (
130
+ len(dataset_with_embeddings.nodes[node_type]) == 0
131
+ or embedding_name in dataset_with_embeddings.nodes[node_type].columns
132
+ )
tests/test_dgl.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Unit tests for the `dgl` module."""
tests/test_embedder.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Unit tests for the `embedder` module."""
tests/test_id_updator.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Unit tests for the `id_updator` module."""
tests/test_image.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Unit tests for the `image` module."""
tests/test_twitter.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Unit tests for the `twitter` module."""