pmkhanh7890 commited on
Commit
22e1b62
·
0 Parent(s):
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +245 -0
  2. .pre-commit-config.yaml +53 -0
  3. .pre-commit-setting.toml +22 -0
  4. .sample-env +4 -0
  5. app.py +400 -0
  6. application.py +137 -0
  7. demo.py +309 -0
  8. pyproject.toml +21 -0
  9. readme.md +70 -0
  10. requirements.txt +34 -0
  11. src/__init__.py +0 -0
  12. src/application/url_reader.py +76 -0
  13. src/images/CNN_model_classifier.py +63 -0
  14. src/images/Diffusion/Final_Report.pdf +0 -0
  15. src/images/Diffusion/Pipfile +29 -0
  16. src/images/Diffusion/Pipfile.lock +0 -0
  17. src/images/Diffusion/README.md +72 -0
  18. src/images/Diffusion/combine_laion_script.ipynb +117 -0
  19. src/images/Diffusion/data_split.py +80 -0
  20. src/images/Diffusion/dataloader.py +228 -0
  21. src/images/Diffusion/diffusion_data_loader.py +233 -0
  22. src/images/Diffusion/diffusion_model_classifier.py +242 -0
  23. src/images/Diffusion/evaluation.ipynb +187 -0
  24. src/images/Diffusion/model.py +307 -0
  25. src/images/Diffusion/sample_laion_script.ipynb +73 -0
  26. src/images/Diffusion/scrape.py +149 -0
  27. src/images/Diffusion/utils_sampling.py +94 -0
  28. src/images/Diffusion/visualizations.ipynb +196 -0
  29. src/images/README.md +64 -0
  30. src/images/Search_Image/Bing_search.py +93 -0
  31. src/images/Search_Image/image_difference.py +0 -0
  32. src/images/Search_Image/image_model_share.py +142 -0
  33. src/images/Search_Image/search.py +56 -0
  34. src/images/Search_Image/search_2.py +150 -0
  35. src/images/Search_Image/search_yandex.py +177 -0
  36. src/images/diffusion_data_loader.py +229 -0
  37. src/images/diffusion_model_classifier.py +293 -0
  38. src/images/diffusion_utils_sampling.py +94 -0
  39. src/images/image_demo.py +73 -0
  40. src/main.py +51 -0
  41. src/texts/MAGE/.gradio/flagged/dataset1.csv +2 -0
  42. src/texts/MAGE/LICENSE +201 -0
  43. src/texts/MAGE/README.md +258 -0
  44. src/texts/MAGE/app.py +74 -0
  45. src/texts/MAGE/deployment/__init__.py +1 -0
  46. src/texts/MAGE/deployment/prepare_testbeds.py +348 -0
  47. src/texts/MAGE/deployment/utils.py +294 -0
  48. src/texts/MAGE/main.py +65 -0
  49. src/texts/MAGE/requirements.txt +51 -0
  50. src/texts/MAGE/training/longformer/main.py +666 -0
.gitignore ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ models/
2
+ data/
3
+ **/model_checkpoints
4
+ **/outputs
5
+ training_with_callbacks/
6
+ *.ipynb
7
+
8
+ # Byte-compiled / optimized / DLL files
9
+ __pycache__/
10
+ *.py[cod]
11
+ *$py.class
12
+
13
+ # C extensions
14
+ *.so
15
+
16
+ # Distribution / packaging
17
+ .Python
18
+ build/
19
+ develop-eggs/
20
+ dist/
21
+ downloads/
22
+ eggs/
23
+ .eggs/
24
+ lib/
25
+ lib64/
26
+ parts/
27
+ sdist/
28
+ var/
29
+ wheels/
30
+ share/python-wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ cover
57
+ .hypothesis/
58
+ .pytest_cache/
59
+ cover/
60
+
61
+ # Translations
62
+ *.mo
63
+ *.pot
64
+
65
+ # Django stuff:
66
+ *.log
67
+ local_settings.py
68
+ db.sqlite3
69
+ db.sqlite3-journal
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+
81
+ # PyBuilder
82
+ .pybuilder/
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # IPython
89
+ profile_default/
90
+ ipython_config.py
91
+
92
+ # pyenv
93
+ # For a library or package, you might want to ignore these files since the code is
94
+ # intended to run in multiple environments; otherwise, check them in:
95
+ # .python-version
96
+
97
+ # pipenv
98
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
100
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
101
+ # install all needed dependencies.
102
+ #Pipfile.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ #poetry.lock
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ #pdm.lock
114
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
115
+ # in version control.
116
+ # https://pdm.fming.dev/#use-with-ide
117
+ .pdm.toml
118
+
119
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
120
+ __pypackages__/
121
+
122
+ # Celery stuff
123
+ celerybeat-schedule
124
+ celerybeat.pid
125
+
126
+ # SageMath parsed files
127
+ *.sage.py
128
+
129
+ # Environments
130
+ .env
131
+ .venv
132
+ .venv312
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # MacOS
171
+ .DS_Store
172
+
173
+ # Frontend
174
+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
175
+
176
+ # misc
177
+ *.pem
178
+
179
+ # debug
180
+ npm-debug.log*
181
+ yarn-debug.log*
182
+ yarn-error.log*
183
+ .pnpm-debug.log*
184
+
185
+ # vercel
186
+ .vercel
187
+
188
+ # Pycharm
189
+ .idea
190
+
191
+ # Env vars - to be updated
192
+ /infra/ci/secret.yaml
193
+
194
+ # Local .terraform directories
195
+ **/.terraform/*
196
+
197
+ # .tfstate files
198
+ *.tfstate
199
+ *.tfstate.*
200
+
201
+ # Exclude all .tfvars files, which are likely to contain sensitive data, such as
202
+ # password, private keys, and other secrets. These should not be part of version
203
+ # control as they are data points which are potentially sensitive and subject
204
+ # to change depending on the environment.
205
+ *.tfvars
206
+ *.tfvars.json
207
+
208
+ # Ignore override files as they are usually used to override resources locally and so
209
+ # are not checked in
210
+ override.tf
211
+ override.tf.json
212
+ *_override.tf
213
+ *_override.tf.json
214
+
215
+ # Include override files you do wish to add to version control using negated pattern
216
+ # !example_override.tf
217
+
218
+ # Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan
219
+ # example: *tfplan*
220
+
221
+ # Ignore CLI configuration files
222
+ .terraformrc
223
+ terraform.rc
224
+ .terraform.lock.hcl
225
+ # ignore .vscode
226
+ .vscode
227
+
228
+ # Ignore sensitive data - k8s env vars
229
+ infra/environments/chatbot-dev/dev_secret.yaml
230
+ infra/environments/chatbot-prod/prod_secret.yaml
231
+ infra/environments/tt-chatbot-prod/prod_secret.yaml
232
+
233
+ # yarn file
234
+ yarn.lock
235
+
236
+ # ignore migrations django
237
+ **/migrations/**
238
+ !**/migrations
239
+ !**/migrations/__init__.py
240
+
241
+ # Gradio
242
+ **/.gradio
243
+
244
+ # Lightning
245
+ **/lightning_logs
.pre-commit-config.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+ repos:
4
+ - repo: https://github.com/pre-commit/pre-commit-hooks
5
+ rev: v5.0.0
6
+ hooks:
7
+ #- id: check-added-large-files
8
+ - id: fix-byte-order-marker
9
+ - id: check-case-conflict
10
+ - id: check-json
11
+ - id: check-yaml
12
+ args: ['--unsafe']
13
+ - id: detect-aws-credentials
14
+ args: [--allow-missing-credentials]
15
+ - id: detect-private-key
16
+ - id: end-of-file-fixer
17
+ - id: mixed-line-ending
18
+ - id: trailing-whitespace
19
+ - repo: https://github.com/asottile/add-trailing-comma
20
+ rev: v3.1.0
21
+ hooks:
22
+ - id: add-trailing-comma
23
+ - repo: https://github.com/pycqa/isort
24
+ rev: 5.13.2
25
+ hooks:
26
+ - id: isort
27
+ name: isort (python)
28
+ args: [--settings-path=pyproject.toml]
29
+ - id: isort
30
+ name: isort (cython)
31
+ types: [cython]
32
+ - id: isort
33
+ name: isort (pyi)
34
+ types: [pyi]
35
+ - repo: https://github.com/psf/black
36
+ rev: 24.10.0
37
+ hooks:
38
+ - id: black
39
+ args: [--config=pyproject.toml]
40
+ - repo: https://github.com/pycqa/flake8.git
41
+ rev: 6.1.0
42
+ hooks:
43
+ - id: flake8
44
+ args: [--ignore, "E203, W503", --max-line-length, "79"]
45
+ - repo: https://github.com/kynan/nbstripout
46
+ rev: 0.8.1
47
+ hooks:
48
+ - id: nbstripout
49
+ - repo: https://github.com/asottile/pyupgrade
50
+ rev: v3.19.0
51
+ hooks:
52
+ - id: pyupgrade
53
+ args: [--py36-plus]
.pre-commit-setting.toml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+ [tool.black]
4
+ line-length = 79
5
+ include = '\.pyi?$'
6
+ exclude = '''
7
+ /(
8
+ \.git
9
+ | \.idea
10
+ | \.pytest_cache
11
+ | \.tox
12
+ | \.venv
13
+ | _build
14
+ | buck-out
15
+ | build
16
+ | dist
17
+ )/
18
+ '''
19
+
20
+ [flake8]
21
+ ignore = E203, W503
22
+ max-line-length = 79
.sample-env ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [API_KEY]
2
+ OPENAI_API_KEY=your_api_key # Replace with your actual OpenAI API key
3
+ GEMINI_API_KEY=your_api_key
4
+ TOGETHER_API_KEY=your_api_key
app.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import torchvision.transforms as transforms
4
+ from google_img_source_search import ReverseImageSearcher
5
+
6
+ # from src.images.CNN_model_classifier import predict_cnn
7
+ # from src.images.diffusion_model_classifier import (
8
+ # ImageClassifier,
9
+ # predict_single_image,
10
+ # )
11
+
12
+ warnings.simplefilter(
13
+ action="ignore",
14
+ category=FutureWarning,
15
+ ) # disable FutureWarning
16
+
17
+ import gradio as gr # noqa: E402
18
+ from transformers import ( # noqa: E402
19
+ AutoModelForSequenceClassification,
20
+ AutoTokenizer,
21
+ pipeline,
22
+ )
23
+
24
+ from src.texts.MAGE.deployment import ( # noqa: E402
25
+ detect,
26
+ preprocess,
27
+ )
28
+ from src.texts.PASTED.pasted_lexicon import Detector # noqa: E402
29
+ from src.texts.Search_Text.search import ( # noqa: E402
30
+ get_important_sentences,
31
+ get_keywords,
32
+ is_human_written,
33
+ )
34
+ from src.images.Search_Image.search import (
35
+ compare_images,
36
+ get_image_from_path,
37
+ get_image_from_url,
38
+ )
39
+
40
+
41
+ def convert_score_range(score):
42
+ """
43
+ Converts a score from the range [0, 1] to [-1, 1].
44
+
45
+ Args:
46
+ score: The original score in the range [0, 1].
47
+
48
+ Returns:
49
+ The converted score in the range [-1, 1].
50
+ """
51
+
52
+ return 2 * score - 1
53
+
54
+
55
+ def generate_highlighted_text(text_scores):
56
+ """
57
+ Generates a highlighted text string based on the given text and scores.
58
+
59
+ Args:
60
+ text_scores: A list of tuples, where each tuple contains a text
61
+ segment and its score.
62
+
63
+ Returns:
64
+ A string of HTML code with highlighted text.
65
+ """
66
+ highlighted_text = ""
67
+ for text, score in text_scores:
68
+ # Map score to a color using a gradient
69
+ color = f"rgba(255, 0, 0, {1 - score})" # Red to green gradient
70
+ highlighted_text += (
71
+ f"<span style='background-color: {color}'>{text}</span>" # noqa
72
+ )
73
+ return highlighted_text
74
+
75
+
76
+ def separate_characters_with_mask(text, mask):
77
+ """Separates characters in a string and pairs them with a mask sign.
78
+
79
+ Args:
80
+ text: The input string.
81
+
82
+ Returns:
83
+ A list of tuples, where each tuple contains a character and a mask.
84
+ """
85
+
86
+ return [(char, mask) for char in text]
87
+
88
+
89
+ def detect_ai_text(model_name, search_engine, text):
90
+ if search_engine is True:
91
+ keywords = get_keywords(text)
92
+ important_sentences = get_important_sentences(text, keywords)
93
+ predictions = is_human_written(important_sentences[0])
94
+ print("keywords: ", keywords)
95
+ print("important_sentences: ", important_sentences)
96
+ print("predictions: ", predictions)
97
+ if predictions == -1:
98
+ caption = "[Found exact match] "
99
+ text_scores = list(zip([caption, text], [0, predictions]))
100
+ print("text_scores: ", text_scores)
101
+ return text_scores
102
+
103
+ if model_name == "SimLLM":
104
+ tokenize_input = SimLLM_tokenizer(text, return_tensors="pt")
105
+ outputs = SimLLM_model(**tokenize_input)
106
+ predictions = outputs.logits.argmax(dim=-1).item()
107
+ if predictions == 0:
108
+ predictions = "human-written"
109
+ else:
110
+ predictions = "machine-generated"
111
+
112
+ elif model_name == "MAGE":
113
+ processed_text = preprocess(text)
114
+ predictions = detect(
115
+ processed_text,
116
+ MAGE_tokenizer,
117
+ MAGE_model,
118
+ device,
119
+ )
120
+
121
+ elif model_name == "chatgpt-detector-roberta":
122
+ predictions = roberta_pipeline_en(text)[0]["label"]
123
+ if predictions == "Human":
124
+ predictions = "human-written"
125
+ else: # ChatGPT
126
+ predictions = "machine-generated"
127
+ elif model_name == "PASTED-Lexical":
128
+ predictions = detector(text)
129
+
130
+ if model_name != "PASTED-Lexical":
131
+ text_scores = list(zip([text], [predictions]))
132
+ else:
133
+ text_scores = []
134
+ for text, score in predictions:
135
+ new_score = convert_score_range(score) # normalize score
136
+ text_scores.append((text, new_score))
137
+
138
+ return text_scores
139
+
140
+
141
+ diffusion_model_path = (
142
+ "src/images/Diffusion/model_checkpoints/"
143
+ "image-classifier-step=7007-val_loss=0.09.ckpt"
144
+ )
145
+ cnn_model_path = "src/images/CNN/model_checkpoints/blur_jpg_prob0.5.pth"
146
+
147
+
148
+ def detect_ai_image(input_image_path, search_engine):
149
+ # if search_engine is True:
150
+ # Search image
151
+
152
+ rev_img_searcher = ReverseImageSearcher()
153
+ search_items = rev_img_searcher.search_by_file(input_image_path)
154
+ min_result_difference = 5000
155
+ result_image_url = ""
156
+ input_image = get_image_from_path(input_image_path)
157
+
158
+ for search_item in search_items:
159
+ # print(f'Title: {search_item.page_title}')
160
+ # print(f'Site: {search_item.page_url}')
161
+ # print(f'Img: {search_item.image_url}\n')
162
+
163
+ # Compare each search result image with the input image
164
+ result_image = get_image_from_url(search_item.image_url)
165
+ # input_image = get_image_from_url(search_item.image_url)
166
+ result_difference = compare_images(result_image, input_image)
167
+
168
+ print(f"Difference with search result: {result_difference}")
169
+ print(f"Result image url: {search_item.page_url}\n")
170
+
171
+ if min_result_difference > result_difference:
172
+ min_result_difference = result_difference
173
+ result_image_url = search_item.image_url
174
+ result_page_url = search_item.page_url
175
+
176
+
177
+ if result_difference == 0:
178
+ break
179
+
180
+
181
+ if min_result_difference == 0:
182
+ result = f"<h1>Input image is LIKELY SIMILAR to image from:</h1>"\
183
+ f"<ul>"\
184
+ f'<li>\nPage URL: <a href="url">{result_page_url}</a></li>'\
185
+ f'<li>\nImage URL: <a href="url">{result_image_url}</a></li>'\
186
+ f"<li>\nDifference score: {min_result_difference}</li>"\
187
+ f"</ul>"
188
+ elif 10 > min_result_difference > 0:
189
+ result = f"<h1>Input image is potentially a VARIATRION from:</h1>"\
190
+ f"<ul>"\
191
+ f'<li>\nPage URL: <a href="url">{result_page_url}</a></li>'\
192
+ f'<li>\nImage URL: <a href="url">{result_image_url}</a></li>'\
193
+ f"<li>\nDifference score: {min_result_difference}</li>"\
194
+ f"</ul>"
195
+ elif min_result_difference < 5000:
196
+ result = f"<h1>Input image is not similar to any search results.</h1>"\
197
+ f"<ul>"\
198
+ f'<li>\nPage URL: <a href="url">{result_page_url}</a></li>'\
199
+ f'<li>\nImage URL: <a href="url">{result_image_url}</a></li>'\
200
+ f"<li>\nDifference score: {min_result_difference}</li>"\
201
+ f"</ul>"
202
+ else:
203
+ result = f"<h1>No search result found.</h1>"\
204
+
205
+ return result
206
+
207
+ # def get_prediction_diffusion(image):
208
+ # model = ImageClassifier.load_from_checkpoint(diffusion_model_path)
209
+
210
+ # prediction = predict_single_image(image, model)
211
+ # return (prediction >= 0.5, prediction)
212
+
213
+ # def get_prediction_cnn(image):
214
+ # prediction = predict_cnn(image, cnn_model_path)
215
+ # return (prediction >= 0.5, prediction)
216
+
217
+ # # Define the transformations for the image
218
+ # transform = transforms.Compose(
219
+ # [
220
+ # transforms.Resize((224, 224)), # Image size expected by ResNet50
221
+ # transforms.ToTensor(),
222
+ # transforms.Normalize(
223
+ # mean=[0.485, 0.456, 0.406],
224
+ # std=[0.229, 0.224, 0.225],
225
+ # ),
226
+ # ],
227
+ # )
228
+ # image_tensor = transform(inp)
229
+ # pred_diff, prob_diff = get_prediction_diffusion(image_tensor)
230
+ # pred_cnn, prob_cnn = get_prediction_cnn(image_tensor)
231
+ # verdict = (
232
+ # "AI Generated" if (pred_diff or pred_cnn) else "No GenAI detected"
233
+ # )
234
+ # return (
235
+ # f"<h1>{verdict}</h1>"
236
+ # f"<ul>"
237
+ # f"<li>Diffusion detection score: {prob_diff:.1%} "
238
+ # f"{'(MATCH)' if pred_diff else ''}</li>"
239
+ # f"<li>CNN detection score: {prob_cnn:.1%} "
240
+ # f"{'(MATCH)' if pred_cnn else ''}</li>"
241
+ # f"</ul>"
242
+ # )
243
+
244
+
245
+ # Define GPUs
246
+ device = "cpu" # use 'cuda:0' if GPU is available
247
+
248
+ # init MAGE
249
+ model_dir = "yaful/MAGE" # model in huggingface
250
+ MAGE_tokenizer = AutoTokenizer.from_pretrained(model_dir)
251
+ MAGE_model = AutoModelForSequenceClassification.from_pretrained(model_dir).to(
252
+ device,
253
+ )
254
+
255
+ # init chatgpt-detector-roberta
256
+ model_dir = "Hello-SimpleAI/chatgpt-detector-roberta" # model in huggingface
257
+ roberta_pipeline_en = pipeline(task="text-classification", model=model_dir)
258
+
259
+ # init PASTED
260
+ model_dir = "linzw/PASTED-Lexical"
261
+ detector = Detector(model_dir, device)
262
+
263
+ # init SimLLM
264
+ model_path = "./models/single_model_detector"
265
+ SimLLM_tokenizer = AutoTokenizer.from_pretrained(model_path)
266
+ SimLLM_model = AutoModelForSequenceClassification.from_pretrained(model_path)
267
+
268
+ # Init variable for UI
269
+ title = """
270
+ <center>
271
+
272
+ <h1> AI-generated content detection </h1>
273
+ <b> Demo by NICT & Tokyo Techies <b>
274
+
275
+ </center>
276
+ """
277
+
278
+ examples = [
279
+ [
280
+ "SimLLM",
281
+ False,
282
+ """\
283
+ The BBC's long-running consumer rights series Watchdog is to end as a \
284
+ standalone programme, instead becoming part of The One Show. Watchdog \
285
+ began in 1980 as a strand of Nationwide, but proved so popular it \
286
+ became a separate programme in 1985. Co-host Steph McGovern has moved \
287
+ to Channel 4, but Matt Allwright and Nikki Fox will stay to front the \
288
+ new strand. The BBC said they would investigate viewer complaints all \
289
+ year round rather than for two series a year.
290
+ """,
291
+ ],
292
+ [
293
+ "chatgpt-detector-roberta",
294
+ False,
295
+ """\
296
+ Artificial intelligence (AI) is the science of making machines \
297
+ intelligent. It enables computers to learn from data, recognize \
298
+ patterns, and make decisions. AI powers many technologies we use \
299
+ daily, from voice assistants to self-driving cars. It's rapidly \
300
+ evolving, promising to revolutionize various industries and reshape \
301
+ the future.""",
302
+ ],
303
+ ]
304
+
305
+ model_remark = """<left>
306
+ Model sources:
307
+ <a href="https://github.com/Tokyo-Techies/prj-nict-ai-content-detection">SimLLM</a>,
308
+ <a href="https://github.com/yafuly/MAGE">MAGE</a>,
309
+ <a href="https://huggingface.co/Hello-SimpleAI/chatgpt-detector-roberta">chatgpt-detector-roberta</a>,
310
+ <a href="https://github.com/Linzwcs/PASTED">PASTED-Lexical</a>.
311
+ </left>
312
+ """ # noqa: E501
313
+
314
+ image_samples = [
315
+ ["src/images/samples/fake_dalle.jpg", "Generated (Dall-E)"],
316
+ ["src/images/samples/fake_midjourney.png", "Generated (MidJourney)"],
317
+ ["src/images/samples/fake_stable.jpg", "Generated (Stable Diffusion)"],
318
+ ["src/images/samples/fake_cnn.png", "Generated (GAN)"],
319
+ ["src/images/samples/real.png", "Organic"],
320
+ [
321
+ "https://p.potaufeu.asahi.com/1831-p/picture/27695628/89644a996fdd0cfc9e06398c64320fbe.jpg", # noqa E501
322
+ "Internet GenAI",
323
+ ],
324
+ ]
325
+ image_samples_path = [i[0] for i in image_samples]
326
+
327
+ # UI
328
+ with gr.Blocks() as demo:
329
+ with gr.Row():
330
+ gr.HTML(title)
331
+ with gr.Row():
332
+ with gr.Tab("Text"):
333
+ with gr.Row():
334
+ with gr.Column():
335
+ model = gr.Dropdown(
336
+ [
337
+ "SimLLM",
338
+ "MAGE",
339
+ "chatgpt-detector-roberta",
340
+ "PASTED-Lexical",
341
+ ],
342
+ label="Detection model",
343
+ )
344
+ search_engine = gr.Checkbox(label="Use search engine")
345
+ gr.HTML(model_remark)
346
+ with gr.Column():
347
+ text_input = gr.Textbox(
348
+ label="Input text",
349
+ placeholder="Enter text here...",
350
+ lines=5,
351
+ )
352
+
353
+ output = gr.HighlightedText(
354
+ label="Detection results",
355
+ combine_adjacent=True,
356
+ show_legend=True,
357
+ color_map={
358
+ "human-written": "#7d58cf",
359
+ "machine-generated": "#e34242",
360
+ },
361
+ )
362
+
363
+ gr.Examples(
364
+ examples=examples,
365
+ inputs=[model, search_engine, text_input],
366
+ )
367
+ model.change(
368
+ detect_ai_text,
369
+ inputs=[model, search_engine, text_input],
370
+ outputs=output,
371
+ )
372
+ search_engine.change(
373
+ detect_ai_text,
374
+ inputs=[model, search_engine, text_input],
375
+ outputs=output,
376
+ )
377
+ text_input.change(
378
+ detect_ai_text,
379
+ inputs=[model, search_engine, text_input],
380
+ outputs=output,
381
+ )
382
+ with gr.Tab("Images"):
383
+ with gr.Row():
384
+ input_image = gr.Image(type="filepath")
385
+ with gr.Column():
386
+ output_image = gr.Markdown(height=400)
387
+ gr.Examples(
388
+ examples=image_samples,
389
+ inputs=input_image,
390
+ )
391
+
392
+ input_image.change(
393
+ detect_ai_image,
394
+ inputs=input_image,
395
+ outputs=output_image,
396
+ )
397
+
398
+
399
+ # demo.launch(share=True)
400
+ demo.launch(allowed_paths=image_samples_path, share=True)
application.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ import openai
5
+ import requests
6
+ from PIL import Image
7
+ import re
8
+
9
+ from src.application.url_reader import URLReader
10
+
11
+ OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
12
+ openai.api_key = os.getenv('OPENAI_API_KEY')
13
+ GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
14
+ SEARCH_ENGINE_ID = os.getenv('SEARCH_ENGINE_ID')
15
+
16
+ def load_url(url):
17
+ """
18
+ Load content from the given URL.
19
+ """
20
+ content = URLReader(url)
21
+ image = None
22
+ header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36'}
23
+ try:
24
+ response = requests.get(
25
+ url,
26
+ headers = header,
27
+ stream = True
28
+ )
29
+ response.raise_for_status() # Raise an exception for bad status codes
30
+
31
+ image_response = requests.get(content.top_image, stream=True)
32
+ try:
33
+ image = Image.open(image_response.raw)
34
+ except:
35
+ print(f"Error loading image from {content.top_image}")
36
+
37
+ except (requests.exceptions.RequestException, FileNotFoundError) as e:
38
+ print(f"Error fetching image: {e}")
39
+
40
+ return content.title, content.text, image
41
+
42
+
43
+ def replace_terms(text, input_term, destination_term):
44
+ # Replace input_term with destination_term in the text
45
+ modified_text = re.sub(input_term, destination_term, text)
46
+ return modified_text
47
+
48
+ def generate_content(model1, model2, title, content):
49
+ # Generate text using the selected models
50
+ full_content = ""
51
+ input_type = ""
52
+ if title and content:
53
+ full_content = title + "\n" + content
54
+ input_type = "title and content"
55
+ elif title:
56
+ full_content = title
57
+ input_type = "title"
58
+ elif content:
59
+ full_content = title
60
+ input_type = "content"
61
+
62
+ def generate_text(model, full_context, input_type):
63
+ # Generate text using the selected model
64
+ if input_type == "":
65
+ prompt = "Generate a random fake news article"
66
+ else:
67
+ prompt = f"Generate a fake news article (title and content) based on the following {input_type}: {full_context}"
68
+
69
+ try:
70
+ response = openai.ChatCompletion.create(
71
+ model=model,
72
+ messages=[
73
+ {"role": "user", "content": prompt}
74
+ ]
75
+ )
76
+ return response.choices[0].message.content
77
+
78
+ except openai.error.OpenAIError as e:
79
+ print(f"Error interacting with OpenAI API: {e}")
80
+ return "An error occurred while processing your request."
81
+
82
+ # Define the GUI
83
+ with gr.Blocks() as demo:
84
+ gr.Markdown("# Fake News Detection")
85
+
86
+ with gr.Row():
87
+ with gr.Column(scale=1):
88
+ gr.Markdown("## Settings")
89
+ gr.Markdown("This tool generates fake news by modifying the content of a given URL.")
90
+
91
+ with gr.Accordion("1. Enter a URL"):
92
+ #gr.Markdown(" 1. Enter a URL.")
93
+ url_input = gr.Textbox(
94
+ label="URL",
95
+ value="https://bbc.com/future/article/20250110-how-often-you-should-wash-your-towels-according-to-science",
96
+ )
97
+ load_button = gr.Button("Load an URL...")
98
+
99
+ with gr.Accordion("2. Select a content-generation model", open=True):
100
+ with gr.Row():
101
+ model1_dropdown = gr.Dropdown(choices=["GPT 4o", "GPT 4o-mini"], label="Text-generation model")
102
+ model2_dropdown = gr.Dropdown(choices=["Dall-e", "Stable Diffusion"], label="Image-generation model")
103
+ generate_button = gr.Button("Random generation...")
104
+
105
+ with gr.Accordion("3. Replace any terms", open=True):
106
+ with gr.Row():
107
+ input_term_box = gr.Textbox(label="Input Term")
108
+ destination_term_box = gr.Textbox(label="Destination Term")
109
+ replace_button = gr.Button("Replace term...")
110
+
111
+ process_button = gr.Button("Process")
112
+
113
+ with gr.Column(scale=2):
114
+ gr.Markdown("## News contents")
115
+ title_input = gr.Textbox(label="Title", value="")
116
+ with gr.Row():
117
+ image_view = gr.Image(label="Image")
118
+ content_input = gr.Textbox(label="Content", value="", lines=15)
119
+
120
+
121
+
122
+ # Connect events
123
+ load_button.click(
124
+ load_url,
125
+ inputs=url_input,
126
+ outputs=[title_input, content_input, image_view]
127
+ )
128
+ replace_button.click(replace_terms,
129
+ inputs=[content_input, input_term_box, destination_term_box],
130
+ outputs=content_input)
131
+ process_button.click(generate_text,
132
+ inputs=[url_input, model1_dropdown, model2_dropdown, input_term_box, destination_term_box, title_input, content_input],
133
+ outputs=[title_input, content_input])
134
+
135
+ #url_input.change(load_image, inputs=url_input, outputs=image_view)
136
+
137
+ demo.launch()
demo.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from src.images.Search_Image.search import find_similar_img_from_url
4
+
5
+ import re
6
+
7
+ import gradio as gr
8
+
9
+ from src.images.Search_Image.image_model_share import (
10
+ image_generation_detection,
11
+ )
12
+ from src.texts.Search_Text._text_detection_share import (
13
+ UNKNOWN,
14
+ abstract_detect_generated_text,
15
+ )
16
+ from src.texts.Search_Text.fake_text_generation_share import (
17
+ highlight_overlap_by_word_to_list,
18
+ )
19
+
20
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
21
+
22
+ TEMP_IMAGE = "temp_image.jpg"
23
+ TEMP_INPUT_IMAGE = "temp_input_image.jpg"
24
+
25
+ HUMAN_IMAGE = "data/test_data/human_news.jpg"
26
+
27
+ HUMAN_CAPTION = "Stoke City have secured West Brom striker Saido Berahino for £12 million on a five-and-a-half-year contract."
28
+ HUMAN_CONTENT = """
29
+ Tracey Jolliffe has already donated a kidney, 16 eggs and 80 pints of blood, and intends to leave her brain to science. She is now hoping to give away part of her liver to a person she may never meet.
30
+ "If I had another spare kidney, I'd do it again," Tracey tells the BBC's Victoria Derbyshire programme.
31
+ She is what is known as an "altruistic donor" - someone willing to give away an organ to potentially help save the life of a complete stranger.
32
+ A microbiologist in the NHS, and the daughter of two nurses, she has spent her life learning about the importance of healthcare from a professional standpoint.
33
+ But she has also been keen to make a difference on a personal level.
34
+ "I signed up to donate blood, and to the bone marrow register, when I was 18," she says.
35
+ Now 50, her wish to donate has become gradually more expansive.
36
+ In 2012, she was one of fewer than 100 people that year to donate a kidney without knowing the recipient's identity - and now supports the charity Give A Kidney, encouraging others to do the same.
37
+ As of 30 September 2016, 5,126 people remain on the NHS kidney transplant waiting list.
38
+ Tracey's kidney donation, in all likelihood, will have saved someone's life.
39
+ "I remind myself of it every day when I wake up," she says, rightly proud of her life-changing actions.
40
+ It was not, however, a decision taken on the spur of a moment.
41
+ Donating a kidney is an "involved process", she says, with suitability assessments taking at least three months to complete.
42
+ Tests leading up to the transplant include X-rays, heart tracing and a special test of kidney function, which involves an injection and a series of blood tests.
43
+ "It is not something to do if you're scared of needles," she jokes.
44
+ The risks associated with donating, however, are relatively low for those deemed healthy enough to proceed, with a mortality rate of about one in 3,000 - roughly the same as having an appendix removed.
45
+ Compared with the general public, NHS Blood and Transplant says, most kidney donors have equivalent - or better - life expectancy than the average person.
46
+ Tracey says she was in hospital for five days after her operation but felt "back to normal" within six weeks.
47
+ """
48
+
49
+ HUMAN_NEWS_CNN = """
50
+ Mayotte authorities fear hunger and disease after cyclone, as death toll rises in Mozambique
51
+ Cyclone Chido caused devastation in Mayotte and authorities are now rushing to prevent disease and hunger spreading in the French overseas territory Sipa USA
52
+ Authorities in Mayotte were racing on Tuesday to stop hunger, disease and lawlessness from spreading in the French overseas territory after the weekend’s devastating cyclone, while Mozambique reported dozens of deaths from the storm.
53
+ Hundreds or even thousands could be dead in Mayotte, which took the strongest hit from Cyclone Chido, French officials have said. The storm laid waste to large parts of the archipelago off east Africa, France’s poorest overseas territory, before striking continental Africa.
54
+ With many parts of Mayotte still inaccessible and some victims buried before their deaths could be officially counted, it may take days to discover the full extent of the destruction.
55
+ So far, 22 deaths and more than 1,400 injuries have been confirmed, Ambdilwahedou Soumaila, the mayor of the capital Mamoudzou, told Radio France Internationale on Tuesday morning.
56
+ “The priority today is water and food,” Soumaila said. “There are people who have unfortunately died where the bodies are starting to decompose that can create a sanitary problem.”
57
+ “We don’t have electricity. When night falls, there are people who take advantage of that situation.”
58
+
59
+ Rescue workers operate in storm-hit Mayotte on Wednesday.
60
+ Rescue workers operate in storm-hit Mayotte on Wednesday. Securite Civile via Reuters
61
+ Twenty tonnes of food and water are due to start arriving on Tuesday by air and sea. The French government said late on Monday it expects 50% of water supplies to be restored within 48 hours and 95% within the week.
62
+ France’s interior ministry announced that a curfew would go into effect on Tuesday night from 10 p.m. to 4 a.m. local time.
63
+ Rescue workers have been searching for survivors amid the debris of shantytowns bowled over by 200 kph (124 mph) winds.
64
+ Chido was the strongest storm to strike Mayotte in more than 90 years, French weather service Meteo France said. In Mozambique, it killed at least 34 people, officials said on Tuesday. Another seven died in Malawi.
65
+ Drone footage from Mozambique’s Cabo Delgado province, already experiencing a humanitarian crisis due to an Islamist insurgency, showed razed thatched-roof houses near the beach and personal belongings scattered under the few palm trees still standing.
66
+
67
+ Dispute over immigration
68
+ French President Emmanuel Macron said after an emergency cabinet meeting on Monday that he would visit Mayotte in the coming days, as the disaster quickly fueled a political back-and-forth about immigration, the environment and France’s treatment of its overseas territories.
69
+ Mayotte has been grappling with unrest in recent years, with many residents angry at illegal immigration and inflation.
70
+ More than three-quarters of its roughly 321,000 people live in relative poverty, and about one-third are estimated to be undocumented migrants, most from nearby Comoros and Madagascar.
71
+ The territory has become a stronghold for the far-right National Rally with 60% voting for Marine Le Pen in the 2022 presidential election runoff.
72
+ France’s acting Interior Minister Bruno Retailleau, from the conservative Republicans party, told a news conference in Mayotte that the early warning system had worked “perfectly” but many of the undocumented had not come to designated shelters.
73
+ People stand amid uprooted trees and debris after cyclone Chido hit Mecufi district, Cabo Delgado province, Mozambique, on December 16.
74
+ People stand amid uprooted trees and debris after cyclone Chido hit Mecufi district, Cabo Delgado province, Mozambique, on December 16. UNICEF Mozambique via Reuters
75
+ Other officials have said undocumented migrants may have been afraid to go to shelters for fear of being arrested.
76
+ The toll of the cyclone, Retailleau said in a later post on X, underscored the need to address “the migration question.”
77
+ “Mayotte is the symbol of the drift that (French) governments have allowed to take hold on this issue,” he said. “We will need to legislate so that in Mayotte, like everywhere else on the national territory, France retakes control of its immigration.”
78
+ Left-wing politicians, however, have pointed the finger at what they say is the government’s neglect of Mayotte and failure to prepare for natural disasters linked to climate change.
79
+ Socialist Party chairman Olivier Faure blasted Retailleau’s comments in an X post.
80
+ “He could have interrogated the role of climate change in producing more and more intense climate disasters. He could have rallied against the extreme poverty that makes people more vulnerable to cyclones,” said Faure.
81
+ “No, he has resumed his crusade against migrants.”
82
+ Prime Minister Francois Bayrou, appointed last week to steer France out of a political crisis, faced criticism after he went to the town of Pau, where he is the mayor, to attend a municipal council meeting on Monday, instead of visiting Mayotte.
83
+ """
84
+
85
+ HUMAN_NEWS_CNN_IMAGE = "human_cnn.webp"
86
+ # generate a short news related to sport
87
+
88
+ # opposite
89
+ OPPOSITE_NEWS = """
90
+ Tracey Jolliffe has never donated a kidney, any eggs, or blood, and has no plans to leave her brain to science. She is not considering giving away any part of her liver to someone she knows.
91
+ "If I had another spare kidney, I wouldn't do it again," Tracey tells the BBC's Victoria Derbyshire programme.
92
+ She is not an "altruistic donor" - someone unwilling to give away an organ to potentially save the life of a complete stranger.
93
+ A microbiologist outside the NHS, with parents who were not in healthcare, she has spent her life without focusing on the importance of healthcare from a professional standpoint.
94
+ She has also not been eager to make a difference on a personal level.
95
+ "I never signed up to donate blood, nor to the bone marrow register, when I was 18," she says.
96
+ Now 50, her interest in donating has not expanded.
97
+ In 2012, she was not among the few people that year to donate a kidney without knowing the recipient's identity - and does not support the charity Give A Kidney, discouraging others from doing the same.
98
+ As of 30 September 2016, 5,126 people remain on the NHS kidney transplant waiting list.
99
+ Tracey's decision not to donate a kidney hasn't saved anyone's life.
100
+ "I never think about it when I wake up," she says, indifferent about her choices.
101
+ It was not a decision made after careful consideration.
102
+ Donating a kidney is not an "involved process", she says, with suitability assessments taking less than three months to complete.
103
+ Tests leading up to the transplant do not include X-rays, heart tracing, or a special test of kidney function, which does not involve an injection or any blood tests.
104
+ "It is something to do if you're scared of needles," she jokes.
105
+ The risks associated with donating, however, are relatively high for those not deemed healthy enough to proceed, with a high mortality rate - much greater than having an appendix removed.
106
+ Compared with the general public, NHS Blood and Transplant says, most kidney donors have worse life expectancy than the average person.
107
+ Tracey says she was not in hospital after any operation and did not feel "back to normal" within six weeks.
108
+ """
109
+
110
+ PARAPHASE_NEWS = """
111
+ Tracey Jolliffe has generously donated a kidney, 16 eggs, and 80 pints of blood, and plans to donate her brain to science. She now hopes to donate part of her liver to someone she may never meet. "If I had another spare kidney, I'd do it again," she shares with the BBC's Victoria Derbyshire program. Known as an "altruistic donor," Tracey is willing to donate organs to help save the lives of strangers.
112
+ As a microbiologist in the NHS and the daughter of two nurses, Tracey has always understood the importance of healthcare professionally. However, she also strives to make a personal impact. "I signed up to donate blood and joined the bone marrow register at 18," she explains. Now 50, her desire to donate has expanded over the years.
113
+ In 2012, Tracey was among fewer than 100 people that year who donated a kidney without knowing the recipient. She now supports Give A Kidney, a charity that encourages others to donate. As of 30 September 2016, 5,126 people were on the NHS kidney transplant waiting list. Tracey's kidney donation likely saved a life. "I remind myself of it every day when I wake up," she says, proud of her life-changing decision.
114
+ Donating a kidney was not a spontaneous decision for Tracey. It is a complex process, she explains, with suitability assessments taking at least three months. Pre-transplant tests include X-rays, heart monitoring, and a special kidney function test involving an injection and multiple blood tests. "It's not for those afraid of needles," she jokes.
115
+ For healthy individuals, the risks of donating a kidney are relatively low, with a mortality rate of about one in 3,000, similar to having an appendix removed. According to NHS Blood and Transplant, most kidney donors have the same or better life expectancy compared to the general population. Tracey was hospitalized for five days after her operation and felt "back to normal" within six weeks.
116
+ """
117
+
118
+ MACHINE_IMAGE = "data/test_data/machine_news.png"
119
+ # MACHINE_CAPTION = "Argentina Secures Victory in Thrilling Friendly Match Against Brazil"
120
+ MACHINE_CONTENT = """
121
+ Tracey Jolliffe has already donated a kidney, 16 eggs, and 80 pints of blood, and she intends to leave her brain to science. She is now hoping to give away part of her liver to a person she may never meet.
122
+ "If I had another spare kidney, I'd do it again," Tracey tells the BBC's Victoria Derbyshire programme.
123
+ She is what is known as an "altruistic donor"—someone willing to give away an organ to potentially help save the life of a complete stranger.
124
+ A microbiologist in the NHS and the daughter of two nurses, she has spent her life learning about the importance of healthcare from a professional standpoint. But she has also been keen to make a difference on a personal level. "I signed up to donate blood and to the bone marrow register when I was 18," she says.
125
+ Now 50, her wish to donate has become gradually more expansive. In 2012, she was one of fewer than 100 people that year to donate a kidney without knowing the recipient's identity, and she now supports the charity Give A Kidney, encouraging others to do the same.
126
+ As of 30 September 2016, 5,126 people remain on the NHS kidney transplant waiting list. Tracey's kidney donation, in all likelihood, has saved someone's life. "I remind myself of it every day when I wake up," she says, rightly proud of her life-changing actions.
127
+ It was not, however, a decision taken on the spur of a moment. Donating a kidney is an "involved process," she says, with suitability assessments taking at least three months to complete. Tests leading up to the transplant include X-rays, heart tracing, and a special test of kidney function, which involves an injection and a series of blood tests. "It is not something to do if you're scared of needles," she jokes.
128
+ The risks associated with donating, however, are relatively low for those deemed healthy enough to proceed, with a mortality rate of about one in 3,000—roughly the same as having an appendix removed. Compared with the general public, NHS Blood and Transplant says, most kidney donors have equivalent—or better—life expectancy than the average person.
129
+ Tracey says she was in hospital for five days after her operation but felt "back to normal" within six weeks.
130
+ """
131
+
132
+ HUMAN_BBC_NEWS2 = """
133
+ A message of hope at Washington march
134
+ For such a divisive figure, Donald Trump managed to unify hundreds of thousands of Americans at the Women's March on Washington.
135
+ Moments after Mr Trump was sworn in as the 45th president on Friday, he delivered a thundering speech in which he promised to improve the lives of millions of Americans.
136
+ A day later, throngs of women, men and children streamed into the same area where he made that pledge, in order to take a stand for gender and racial equality.
137
+ Though Mr Trump's named was mentioned frequently, the march, which organisers estimate attracted more than half a million, was not only about the new US president.
138
+ Messages ranged from "Thank you for making me an activist Trump" to "We will not be silenced," but the common thread throughout the patchwork of signs was hope.
139
+ "It's about solidarity and visualising the resistance," said Jonathon Meier, who took a bus from New York.
140
+ "And I think it not only helps with the healing process, but it gives me hope for the next four years."
141
+ A sea of activists, some clad in knitted, pink "pussy" hats and others draped in American flags, ambled about the National Mall, stopping to catch a glimpse of some of the high-profile speakers and singing along to songs like "This Little Light of Mine".
142
+ Peppered among the many protest signs were images of ovaries and female genitals, a nod to concerns over losing access to birth control and abortion care under a Trump administration.
143
+ """
144
+
145
+ FREELY_GENERATION_NEWS = """
146
+ A new study has indicated that criminals and terrorists are increasingly turning to the dark net to purchase weapons. The study, conducted by cybersecurity firm Recorded Future, found that these purchases are being made anonymously and with cryptocurrency, making it difficult for law enforcement agencies to track and intercept them. The dark net is a hidden part of the internet, accessible only through anonymous browsers, where users can buy and sell a variety of illegal goods and services. However, the study found that weapons purchases are becoming more popular on the dark net, with firearms and explosives being the most commonly traded items. Recorded Future's research showed that many of the weapons being sold on the dark net are military-grade, and the study suggests that this is due to the large number of surplus weapons available following military conflicts in various parts of the world. The report also found that the sellers on the dark net are often located in countries with lax gun laws, leading to concerns that these weapons could end up in the hands of criminals and terrorists who could use them to commit acts of violence. The use of cryptocurrency to purchase these weapons adds another layer of difficulty for law enforcement agencies trying to track down those responsible. The anonymity provided by cryptocurrency allows buyers and sellers to conduct their transactions without leaving a trace. The findings of this study serve as a stark reminder of the dangers posed by the dark net, and the need for law enforcement agencies to remain vigilant in their efforts to combat illegal activity on this hidden part of the internet.
147
+ """
148
+
149
+ HUMAN_BBC_NEWS2_IMAGE = "human_bbc_news_2.webp"
150
+
151
+ HIGHLIGHT = "highlight"
152
+
153
+
154
+ def highlight_text(words, indexes):
155
+ final_words = words
156
+ for index in indexes:
157
+ final_words[index] = (
158
+ f"<span style='color:#00FF00; font-weight:bold;'>{words[index]}</span>"
159
+ )
160
+ return " ".join(final_words)
161
+
162
+
163
+ def format_pair(pair):
164
+ input_sentence = highlight_text(pair[0], pair[2])
165
+ source_sentence = highlight_text(pair[1], pair[3])
166
+ return f"<tr><td>{input_sentence}</td><td>{source_sentence}</td></tr>"
167
+
168
+
169
+ def create_table(data):
170
+ table_rows = "\n".join([format_pair(pair) for pair in data])
171
+ return f"""
172
+ <h5> Comparison between input news and source news at the above link</h5>
173
+ <table border="1" style="width:100%; text-align:left; border-collapse:collapse;">
174
+ <thead>
175
+ <tr>
176
+ <th>Input sentence</th>
177
+ <th>Source sentence</th>
178
+ </tr>
179
+ </thead>
180
+ <tbody>
181
+ {table_rows}
182
+ </tbody>
183
+ </table>
184
+ """
185
+
186
+
187
+ with gr.Blocks() as demo:
188
+ image = gr.Image(
189
+ value=HUMAN_IMAGE,
190
+ label="News Image",
191
+ height=200,
192
+ width=200,
193
+ type="filepath",
194
+ )
195
+ content = gr.Textbox(label="Content", lines=3, value=HUMAN_CONTENT)
196
+
197
+ process_btn = gr.Button("Process")
198
+
199
+ """
200
+ 1. human bbc news
201
+ 2. proofreading
202
+ 3. opposite
203
+ 4. human bbc news 2
204
+ 5. human_cnn news
205
+ 6. paraphrase
206
+ 7. freely generation
207
+ """
208
+ gr.Examples(
209
+ examples=[
210
+ [HUMAN_IMAGE, HUMAN_CONTENT],
211
+ [MACHINE_IMAGE, MACHINE_CONTENT],
212
+ [MACHINE_IMAGE, OPPOSITE_NEWS],
213
+ [HUMAN_BBC_NEWS2_IMAGE, HUMAN_BBC_NEWS2],
214
+ [HUMAN_NEWS_CNN_IMAGE, HUMAN_NEWS_CNN],
215
+ [MACHINE_IMAGE, PARAPHASE_NEWS],
216
+ [MACHINE_IMAGE, FREELY_GENERATION_NEWS],
217
+ ],
218
+ inputs=[image, content],
219
+ label="examples",
220
+ example_labels=[
221
+ "human bbc news",
222
+ "proofreading",
223
+ "opposite",
224
+ "human bbc news 2",
225
+ "human cnn news",
226
+ "paraphrase",
227
+ "freely generation",
228
+ ],
229
+ )
230
+
231
+ overall = gr.HTML()
232
+ matching_html = gr.HTML()
233
+
234
+ def process(input_image, content):
235
+ (
236
+ search_engine_prediction,
237
+ SOTA_prediction,
238
+ SOTA_confidence,
239
+ found_url,
240
+ sentence_pairs,
241
+ ) = abstract_detect_generated_text(content)
242
+
243
+ final_table = []
244
+ COLOR_MAPS = {
245
+ "HUMAN": "<span style='color:#FFFF00'>",
246
+ "MACHINE": "<span style='color:red'>",
247
+ }
248
+
249
+ source_image = []
250
+ image_prediction_label, image_confidence = image_generation_detection(
251
+ input_image,
252
+ )
253
+ # [found_img_url, image_different_score] = find_similar_img_from_url(input_image)
254
+
255
+ # if 0 < image_different_score < 10:
256
+ # search_engine_description = f'Most likely generated by {COLOR_MAPS["HUMAN"]} (score = {image_different_score})</span> with evidence link at <a href="{found_img_url}">{found_img_url} </a>'
257
+ # else: # TODO add < 25 which is cropped images
258
+ # search_engine_description = f'Most likely generated by {COLOR_MAPS["MACHINE"]} (score = {image_different_score})</span></a>'
259
+
260
+ for (
261
+ input_sentence,
262
+ source_sentence,
263
+ check_paraphrase,
264
+ ) in sentence_pairs:
265
+ input_words, source_words, input_indexes, source_indexes = (
266
+ highlight_overlap_by_word_to_list(
267
+ input_sentence,
268
+ source_sentence,
269
+ )
270
+ )
271
+ final_table.append(
272
+ (input_words, source_words, input_indexes, source_indexes),
273
+ )
274
+
275
+ if search_engine_prediction == UNKNOWN:
276
+ search_engine_description = "Cannot find any evidence link"
277
+ final_prediction = SOTA_prediction
278
+ else:
279
+ final_prediction = search_engine_prediction
280
+ search_engine_description = f'Most likely generated by {COLOR_MAPS[search_engine_prediction]}{search_engine_prediction}</span> with evidence link at <a href="{found_url}">{found_url} </a>'
281
+
282
+ overall_html_result = f"""
283
+ <h1>Image generation detection</h1>
284
+ <ul>
285
+ <li><strong>Prediction by SOTA method (provided by BDI members):</strong> Most likely generated by {COLOR_MAPS[image_prediction_label]}{image_prediction_label} </span>with confidence = {image_confidence}%</li>
286
+ <li><strong>Prediction by our method (developed by BDI members)</strong>: {search_engine_description}
287
+ </ul>
288
+ <hr>
289
+ <h1>Text generation detection</h1>
290
+ <ul>
291
+ <li><strong>Prediction by SOTA method (https://github.com/Hello-SimpleAI/chatgpt-comparison-detection)</strong>: Most likely generated by {COLOR_MAPS[SOTA_prediction]}{SOTA_prediction} </span>with confidence = {SOTA_confidence}</li>
292
+ <li><strong>Prediction by our method (developed by BDI members)</strong>: {search_engine_description}
293
+ <li><strong>Final prediction by our method (developed by BDI members)</strong>: Most likely generated by {COLOR_MAPS[final_prediction]}{final_prediction}&nbsp;</span></li>
294
+ </ul>
295
+ <p>&nbsp;</p>
296
+ """
297
+ if len(final_table) != 0:
298
+ html_table = create_table(final_table)
299
+ else:
300
+ html_table = ""
301
+ return overall_html_result, html_table
302
+
303
+ process_btn.click(
304
+ process,
305
+ inputs=[image, content],
306
+ outputs=[overall, matching_html],
307
+ )
308
+
309
+ demo.launch(share=False)
pyproject.toml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.black]
2
+ line-length = 79
3
+ include = '\.pyi?$'
4
+ exclude = '''
5
+ /(
6
+ \.git
7
+ | \.idea
8
+ | \.pytest_cache
9
+ | \.tox
10
+ | \.venv
11
+ | _build
12
+ | buck-out
13
+ | build
14
+ | dist
15
+ )/
16
+ '''
17
+
18
+ [tool.isort]
19
+ profile = "black"
20
+ force_grid_wrap=2
21
+ multi_line_output=3
readme.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # [Text] SimLLM: Detecting Sentences Generated by Large Language Models Using Similarity between the Generation and its Re-Generation
2
+
3
+ ## **Getting Started**
4
+ 1. **Clone the repository:**
5
+ ```bash
6
+ git clone https://github.com/Tokyo-Techies/prj-nict-ai-content-detection
7
+ ```
8
+
9
+ 2. **Set up the environment:**
10
+ Using virtual environment:
11
+ ```bash
12
+ python -m venv .venv
13
+ source .venv/bin/activate
14
+ ```
15
+
16
+ 3. **Install dependencies:**
17
+ - Torch: https://pytorch.org/get-started/locally/
18
+ - Others
19
+ ```bash
20
+ pip install -r requirements.txt
21
+ ```
22
+
23
+
24
+ 1. **API Keys** (optional)
25
+ - Obtain API keys for the corresponding models and insert them into the `SimLLM.py` file:
26
+ - ChatGPT: [OpenAI API](https://openai.com/index/openai-api/)
27
+ - Gemini: [Google Gemini API](https://ai.google.dev/gemini-api/docs/api-key)
28
+ - Other LLMs: [Together API](https://api.together.ai/)
29
+
30
+
31
+ 5. **Run the project:**
32
+ - Text only:
33
+ ```bash
34
+ python SimLLM.py
35
+ ```
36
+
37
+ ### Parameters
38
+
39
+ - `LLMs`: List of large language models to use. Available models include 'ChatGPT', 'Yi', 'OpenChat', 'Gemini', 'LLaMa', 'Phi', 'Mixtral', 'QWen', 'OLMO', 'WizardLM', and 'Vicuna'. Default is `['ChatGPT', 'Yi', 'OpenChat']`.
40
+ - `train_indexes`: List of LLM indexes for training. Default is `[0, 1, 2]`.
41
+ - `test_indexes`: List of LLM indexes for testing. Default is `[0]`.
42
+ - `num_samples`: Number of samples. Default is 5000.
43
+
44
+ ### Examples
45
+
46
+ - Running with default parameters:
47
+ `python SimLLM.py`
48
+
49
+ - Running with customized parameters:
50
+ `python SimLLM.py --LLMs ChatGPT --train_indexes 0 --test_indexes 0`
51
+
52
+ ## Dataset
53
+
54
+ The `dataset.csv` file contains both human and generated texts from 12 large language models, including:
55
+ ChatGPT, GPT-4o, Yi, OpenChat, Gemini, LLaMa, Phi, Mixtral, QWen, OLMO, WizardLM, and Vicuna.
56
+
57
+ ## Citation
58
+
59
+ ```bibtex
60
+ @inproceedings{nguyen2024SimLLM,
61
+ title={SimLLM: Detecting Sentences Generated by Large Language Models Using Similarity between the Generation and its Re-generation},
62
+ author={Nguyen-Son, Hoang-Quoc and Dao, Minh-Son and Zettsu, Koji},
63
+ booktitle={The Conference on Empirical Methods in Natural Language Processing},
64
+ year={2024}
65
+ }
66
+ ```
67
+
68
+ ## Acknowledgements
69
+
70
+ - BARTScore: [BARTScore GitHub Repository](https://github.com/neulab/BARTScore)
requirements.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ # TEXT
3
+ accelerate==1.1.1
4
+ datasets==v2.11.0
5
+ evaluate==0.4.3
6
+ google-generativeai==0.8.3
7
+ clean-text==0.6.0
8
+ #grpc
9
+ grpcio==1.68.1
10
+ langchain==0.3.9
11
+ langchain_community==0.3.8
12
+ nltk==3.9.1
13
+ openai==1.55.3
14
+ rouge==1.0.1
15
+ proto-plus==1.25.0
16
+ scikit-learn==1.5.2
17
+ sentence_transformers==3.3.1
18
+ transformers==4.46.3
19
+ xgboost==2.1.3
20
+
21
+ # IMAGES
22
+ torch==2.2.2
23
+ torchvision==0.17.2
24
+ pytorch-lightning==2.4.0
25
+ timm==1.0.12
26
+ opencv-python==4.10.0.84
27
+ torchdata==0.7.1
28
+ invisible-watermark==0.2.0
29
+ google-image-source-search==1.2.2
30
+ requests==2.31.0
31
+ ImageHash==4.3.1
32
+
33
+ # parsing
34
+ PyPDF2
src/__init__.py ADDED
File without changes
src/application/url_reader.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import string
2
+ from bs4 import BeautifulSoup
3
+ from newspaper import article, ArticleException, ArticleBinaryDataException
4
+ import requests
5
+
6
+ class URLReader():
7
+ def __init__(self, url: string, newspaper: bool=True):
8
+ self.url = url
9
+ self.text = None # string
10
+ self.title = None # string
11
+ self.images = None # list of Image objects
12
+ self.top_image = None # Image object
13
+ self.newspaper = newspaper # True if using newspaper4k, False if using BS
14
+ if self.newspaper is True:
15
+ self.extract_content_newspaper()
16
+ else:
17
+ self.extract_content_bs()
18
+
19
+ def extract_content_newspaper(self):
20
+ """
21
+ Use newspaper4k to extracts content from a URL
22
+
23
+ Args:
24
+ url: The URL of the web page.
25
+
26
+ Returns:
27
+ The extracted content (title, text, images)
28
+ """
29
+
30
+ try:
31
+ response = requests.get(self.url)
32
+ response.raise_for_status() # Raise exception for unsuccessful requests
33
+ except requests.exceptions.RequestException as e:
34
+ print(f"Error fetching URL: {e}")
35
+ return None
36
+
37
+ try:
38
+ news = article(url=self.url, fetch_images=True)
39
+ except (ArticleException, ArticleBinaryDataException) as e:
40
+ print(f"\t\t↑↑↑ Error downloading article: {e}")
41
+ return None
42
+
43
+ self.title = news.title
44
+ self.text = news.text
45
+ self.images = news.images
46
+ self.top_image = news.top_image
47
+
48
+ def extract_content_bs(self):
49
+ """
50
+ Use BS and process content
51
+ """
52
+ response = requests.get(self.url)
53
+ response.raise_for_status()
54
+
55
+ response.encoding = response.apparent_encoding
56
+
57
+ try:
58
+ soup = BeautifulSoup(response.content, "html.parser")
59
+ except:
60
+ print(f"Error parsing HTML content from {self.url}")
61
+ return None
62
+
63
+ self.title = soup.title.string.strip() if soup.title else None
64
+
65
+ image_urls = [img['src'] for img in soup.find_all('img')]
66
+ self.images = image_urls
67
+ self.top_image = self.images[0]
68
+
69
+ # Exclude text within specific elements
70
+ for element in soup(["img", "figcaption", "table", "script", "style"]):
71
+ element.extract()
72
+ #text = soup.get_text(separator="\n")
73
+ paragraphs = soup.find_all('p')
74
+ text = ' '.join([p.get_text() for p in paragraphs])
75
+
76
+ self.text = text
src/images/CNN_model_classifier.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import torch.nn
4
+ import torchvision.transforms as transforms
5
+ from PIL import Image
6
+
7
+ from .CNN.networks.resnet import resnet50
8
+
9
+
10
+ def predict_cnn(image, model_path, crop=None):
11
+ model = resnet50(num_classes=1)
12
+ state_dict = torch.load(model_path, map_location="cpu")
13
+ model.load_state_dict(state_dict["model"])
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ model.to(device)
16
+ model.eval()
17
+
18
+ # Transform
19
+ if crop is not None:
20
+ trans_init = [transforms.CenterCrop(crop)]
21
+ print("Cropping to [%i]" % crop)
22
+ trans = transforms.Compose(
23
+ trans_init
24
+ + [
25
+ transforms.ToTensor(),
26
+ transforms.Normalize(
27
+ mean=[0.485, 0.456, 0.406],
28
+ std=[0.229, 0.224, 0.225],
29
+ ),
30
+ ],
31
+ )
32
+
33
+ image = trans(image.convert("RGB"))
34
+
35
+ with torch.no_grad():
36
+ in_tens = image.unsqueeze(0)
37
+ prob = model(in_tens).sigmoid().item()
38
+
39
+ return prob
40
+
41
+
42
+ if __name__ == "__main__":
43
+ parser = argparse.ArgumentParser(
44
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
45
+ )
46
+ parser.add_argument("-f", "--file", default="examples_realfakedir")
47
+ parser.add_argument(
48
+ "-m",
49
+ "--model_path",
50
+ type=str,
51
+ default="weights/blur_jpg_prob0.5.pth",
52
+ )
53
+ parser.add_argument(
54
+ "-c",
55
+ "--crop",
56
+ type=int,
57
+ default=None,
58
+ help="by default, do not crop. specify crop size",
59
+ )
60
+
61
+ opt = parser.parse_args()
62
+ prob = predict_cnn(Image.open(opt.file), opt.model_path, crop=opt.crop)
63
+ print(f"probability of being synthetic: {prob * 100:.2f}%")
src/images/Diffusion/Final_Report.pdf ADDED
Binary file (359 kB). View file
 
src/images/Diffusion/Pipfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [[source]]
2
+ url = "https://pypi.org/simple"
3
+ verify_ssl = true
4
+ name = "pypi"
5
+
6
+ [[source]]
7
+ url = "https://download.pytorch.org/whl/cu121"
8
+ verify_ssl = true
9
+ name = "downloadpytorch"
10
+
11
+ [packages]
12
+ pandas = "*"
13
+ numpy = "*"
14
+ polars = "*"
15
+ requests = "*"
16
+ img2dataset = "*"
17
+ torch = {version = "==2.1.0", index = "downloadpytorch"}
18
+ torchvision = {version = "==0.16.0", index = "downloadpytorch"}
19
+ lightning = "*"
20
+ webdataset = "*"
21
+ matplotlib = "*"
22
+ invisible-watermark = "*"
23
+ torchdata = "*"
24
+ timm = "*"
25
+
26
+ [dev-packages]
27
+
28
+ [requires]
29
+ python_version = "3.11"
src/images/Diffusion/Pipfile.lock ADDED
The diff for this file is too large to render. See raw diff
 
src/images/Diffusion/README.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI-generated image detection
2
+
3
+ This is a group project developed by a team of two individuals.
4
+
5
+ ## Managing Python packages
6
+
7
+ Use of `pipenv` is recommended. The required packages are in `Pipfile`, and can be installed using `pipenv install`.
8
+
9
+ ## Scraping script for Reddit
10
+
11
+ `python scrape.py --subreddit midjourney --flair Showcase`
12
+
13
+ This command will scrape the midjourney subreddit, and filter posts that contain the "Showcase" flair. The default number of images to scrape is 30000. The output will contain a parquet file containing metadata, and a csv file containing the urls.
14
+
15
+ `img2dataset --url_list=urls/midjourney.csv --output_folder=data/midjourney --thread_count=64 --resize_mode=no --output_format=webdataset`
16
+
17
+ This command will download the images in the webdataset format.
18
+
19
+
20
+ ## Laion script for real images
21
+
22
+ `wget -l1 -r --no-parent https://the-eye.eu/public/AI/cah/laion400m-met-release/laion400m-meta/
23
+ mv the-eye.eu/public/AI/cah/laion400m-met-release/laion400m-meta/ .`
24
+
25
+ This command will download a 50GB url metadata dataset in 32 parquet files.
26
+
27
+ `sample_laion_script.ipynb`
28
+
29
+ This script consolidates the parquet files, excludes NSFW images, and selects a subset of 224,917 images.
30
+
31
+ `combine_laion_script`
32
+
33
+ This script combines the outputs from earlier into 1 parquet file.
34
+
35
+ `img2dataset --url_list urls/laion.parquet --input_format "parquet" --url_col "URL" --caption_col "TEXT" --skip_reencode True --output_format webdataset --output_folder data/laion400m_data --processes_count 16 --thread_count 128 --resize_mode no --save_additional_columns '["NSFW","similarity","LICENSE"]' --enable_wandb True`
36
+
37
+ This command will download the images in the webdataset format.
38
+
39
+
40
+ ## Data splitting, preprocessing and loading
41
+
42
+ `data_split.py` splits the data according to 80/10/10. The number of samples:
43
+
44
+ ```
45
+ ./data/laion400m_data: (115346, 14418, 14419)
46
+ ./data/genai-images/StableDiffusion: (22060, 2757, 2758)
47
+ ./data/genai-images/midjourney: (21096, 2637, 2637)
48
+ ./data/genai-images/dalle2: (13582, 1697, 1699)
49
+ ./data/genai-images/dalle3: (12027, 1503, 1504)
50
+ ```
51
+
52
+ Each sample contains image, target label(1 for GenAI images), and domain label(denoting which generator the image is from). The meaning of the domain label is:
53
+
54
+ ```
55
+ DOMAIN_LABELS = {
56
+ 0: "laion",
57
+ 1: "StableDiffusion",
58
+ 2: "dalle2",
59
+ 3: "dalle3",
60
+ 4: "midjourney"
61
+ }
62
+ ```
63
+
64
+ The `load_dataloader()` function in `dataloader.py` returns a `torchdata.dataloader2.DataLoader2` given a list of domains for GenAI images(subset of `[1, 2, 3, 4]`, LAION will always be included). When building the training dataset, data augmentation and class balanced sampling are applied. It is very memory intensive(>20G) and takes some time to fill its buffer before producing batches. Use the dataloader in this way:
65
+
66
+ ```
67
+ for epoch in range(10):
68
+ dl.seed(epoch)
69
+ for d in dl:
70
+ model(d)
71
+ dl.shutdown()
72
+ ```
src/images/Diffusion/combine_laion_script.ipynb ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "pip install pyspark"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "import os\n",
19
+ "current_directory = os.getcwd()\n",
20
+ "print(current_directory)"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "metadata": {},
27
+ "outputs": [],
28
+ "source": [
29
+ "os.chdir(current_directory)\n"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "execution_count": null,
35
+ "metadata": {},
36
+ "outputs": [],
37
+ "source": [
38
+ "import pandas as pd\n",
39
+ "from pyspark.sql import SparkSession\n",
40
+ "from pyspark.sql.functions import col\n",
41
+ "\n",
42
+ "spark = SparkSession.builder.appName(\"CombineParquetFiles\").config(\"spark.executor.memory\", \"8g\").config(\"spark.executor.cores\", \"4\").config(\"spark.executor.instances\", \"3\").config(\"spark.dynamicAllocation.enabled\", \"true\").config(\"spark.task.maxFailures\", 10).getOrCreate()"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": null,
48
+ "metadata": {},
49
+ "outputs": [],
50
+ "source": [
51
+ "parquet_directory_path = '/Users/fionachow/Documents/NYU/CDS/Fall 2023/CSCI - GA 2271 - Computer Vision/Project/laion_sampled'\n",
52
+ "\n",
53
+ "output_parquet_file = '/Users/fionachow/Documents/NYU/CDS/Fall 2023/CSCI - GA 2271 - Computer Vision/Project/laion_combined'\n",
54
+ "\n",
55
+ "df = spark.read.parquet(parquet_directory_path)\n",
56
+ "\n",
57
+ "df_coalesced = df.coalesce(1)\n",
58
+ "\n",
59
+ "df_coalesced.write.mode('overwrite').parquet(output_parquet_file)\n",
60
+ "\n",
61
+ "row_count = df.count()"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "metadata": {},
68
+ "outputs": [],
69
+ "source": [
70
+ "print(row_count)"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "metadata": {},
77
+ "outputs": [],
78
+ "source": [
79
+ "parquet_directory_path = '/Users/fionachow/Documents/NYU/CDS/Fall 2023/CSCI - GA 2271 - Computer Vision/Project/laion_combined/part-00000-0190eea7-02ac-4ea0-86fd-0722308c0c58-c000.snappy.parquet'\n",
80
+ "\n",
81
+ "df = spark.read.parquet(parquet_directory_path)\n",
82
+ "\n",
83
+ "df.show()"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": null,
89
+ "metadata": {},
90
+ "outputs": [],
91
+ "source": [
92
+ "print(df.count())"
93
+ ]
94
+ }
95
+ ],
96
+ "metadata": {
97
+ "kernelspec": {
98
+ "display_name": "bloom",
99
+ "language": "python",
100
+ "name": "python3"
101
+ },
102
+ "language_info": {
103
+ "codemirror_mode": {
104
+ "name": "ipython",
105
+ "version": 3
106
+ },
107
+ "file_extension": ".py",
108
+ "mimetype": "text/x-python",
109
+ "name": "python",
110
+ "nbconvert_exporter": "python",
111
+ "pygments_lexer": "ipython3",
112
+ "version": "3.9.16"
113
+ }
114
+ },
115
+ "nbformat": 4,
116
+ "nbformat_minor": 2
117
+ }
src/images/Diffusion/data_split.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+
4
+ import webdataset as wds
5
+
6
+
7
+ def split_dataset(path, n_train, n_val, n_test, label, domain_label):
8
+ max_file_size = 1000
9
+ input_files = glob.glob(path + "/*.tar")
10
+ src = wds.WebDataset(input_files)
11
+
12
+ train_path_prefix = path + "/train"
13
+ val_path_prefix = path + "/val"
14
+ test_path_prefix = path + "/test"
15
+
16
+ def write_split(dataset, prefix, start, end):
17
+ n_split = end - start
18
+ output_files = [
19
+ f"{prefix}_{i}.tar" for i in range(n_split // max_file_size + 1)
20
+ ]
21
+ for i, output_file in enumerate(output_files):
22
+ print(f"Writing {output_file}")
23
+ with wds.TarWriter(output_file) as dst:
24
+ for sample in dataset.slice(
25
+ start + i * max_file_size,
26
+ min(start + (i + 1) * max_file_size, end),
27
+ ):
28
+ new_sample = {
29
+ "__key__": sample["__key__"],
30
+ "jpg": sample["jpg"],
31
+ "label.cls": label,
32
+ "domain_label.cls": domain_label,
33
+ }
34
+ dst.write(new_sample)
35
+
36
+ write_split(src, train_path_prefix, 0, n_train)
37
+ write_split(src, val_path_prefix, n_train, n_train + n_val)
38
+ write_split(
39
+ src,
40
+ test_path_prefix,
41
+ n_train + n_val,
42
+ n_train + n_val + n_test,
43
+ )
44
+
45
+
46
+ def calculate_sizes(path):
47
+ stat_files = glob.glob(path + "/*_stats.json")
48
+ total = 0
49
+ for f in stat_files:
50
+ with open(f) as stats:
51
+ total += json.load(stats)["successes"]
52
+ n_train = int(total * 0.8)
53
+ n_val = int(total * 0.1)
54
+ n_test = total - n_train - n_val
55
+
56
+ return n_train, n_val, n_test
57
+
58
+
59
+ if __name__ == "__main__":
60
+
61
+ paths = [
62
+ "./data/laion400m_data",
63
+ "./data/genai-images/StableDiffusion",
64
+ "./data/genai-images/midjourney",
65
+ "./data/genai-images/dalle2",
66
+ "./data/genai-images/dalle3",
67
+ ]
68
+
69
+ sizes = []
70
+ for p in paths:
71
+ res = calculate_sizes(p)
72
+ sizes.append(res)
73
+
74
+ domain_labels = [0, 1, 4, 2, 3]
75
+
76
+ for i, p in enumerate(paths):
77
+ print(f"{p}: {sizes[i]}")
78
+ label = 0 if i == 0 else 1
79
+ print(label, domain_labels[i])
80
+ split_dataset(p, *calculate_sizes(p), label, domain_labels[i])
src/images/Diffusion/dataloader.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import collections
3
+ import random
4
+ from typing import Iterator
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import torchdata.datapipes as dp
9
+ from imwatermark import WatermarkEncoder
10
+ from PIL import (
11
+ Image,
12
+ ImageFile,
13
+ )
14
+ from torch.utils.data import DataLoader
15
+ from torchdata.datapipes.iter import (
16
+ Concater,
17
+ FileLister,
18
+ FileOpener,
19
+ SampleMultiplexer,
20
+ )
21
+ from torchvision.transforms import v2
22
+ from tqdm import tqdm
23
+
24
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
25
+ Image.MAX_IMAGE_PIXELS = 1000000000
26
+
27
+ encoder = WatermarkEncoder()
28
+ encoder.set_watermark("bytes", b"test")
29
+
30
+
31
+ DOMAIN_LABELS = {
32
+ 0: "laion",
33
+ 1: "StableDiffusion",
34
+ 2: "dalle2",
35
+ 3: "dalle3",
36
+ 4: "midjourney",
37
+ }
38
+
39
+ N_SAMPLES = {
40
+ 0: (115346, 14418, 14419),
41
+ 1: (22060, 2757, 2758),
42
+ 4: (21096, 2637, 2637),
43
+ 2: (13582, 1697, 1699),
44
+ 3: (12027, 1503, 1504),
45
+ }
46
+
47
+
48
+ @dp.functional_datapipe("collect_from_workers")
49
+ class WorkerResultCollector(dp.iter.IterDataPipe):
50
+ def __init__(self, source: dp.iter.IterDataPipe):
51
+ self.source = source
52
+
53
+ def __iter__(self) -> Iterator:
54
+ yield from self.source
55
+
56
+ def is_replicable(self) -> bool:
57
+ """Method to force data back to main process"""
58
+ return False
59
+
60
+
61
+ def crop_bottom(image, cutoff=16):
62
+ return image[:, :-cutoff, :]
63
+
64
+
65
+ def random_gaussian_blur(image, p=0.01):
66
+ if random.random() < p:
67
+ return v2.functional.gaussian_blur(image, kernel_size=5)
68
+ return image
69
+
70
+
71
+ def random_invisible_watermark(image, p=0.2):
72
+ image_np = np.array(image)
73
+ image_np = np.transpose(image_np, (1, 2, 0))
74
+
75
+ if image_np.ndim == 2: # Grayscale image
76
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2BGR)
77
+ elif image_np.shape[2] == 4: # RGBA image
78
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2BGR)
79
+
80
+ # print(image_np.shape)
81
+ if image_np.shape[0] < 256 or image_np.shape[1] < 256:
82
+ image_np = cv2.resize(
83
+ image_np,
84
+ (256, 256),
85
+ interpolation=cv2.INTER_AREA,
86
+ )
87
+ if random.random() < p:
88
+ return encoder.encode(image_np, method="dwtDct")
89
+ return image_np
90
+
91
+
92
+ def build_transform(split: str):
93
+ train_transform = v2.Compose(
94
+ [
95
+ v2.Lambda(crop_bottom),
96
+ v2.RandomCrop((256, 256), pad_if_needed=True),
97
+ v2.Lambda(random_gaussian_blur),
98
+ v2.RandomGrayscale(p=0.05),
99
+ v2.Lambda(random_invisible_watermark),
100
+ v2.ToImage(),
101
+ ],
102
+ )
103
+
104
+ eval_transform = v2.Compose(
105
+ [
106
+ v2.CenterCrop((256, 256)),
107
+ ],
108
+ )
109
+ transform = train_transform if split == "train" else eval_transform
110
+
111
+ return transform
112
+
113
+
114
+ def dp_to_tuple_train(input_dict):
115
+ transform = build_transform("train")
116
+ return (
117
+ transform(input_dict[".jpg"]),
118
+ input_dict[".label.cls"],
119
+ input_dict[".domain_label.cls"],
120
+ )
121
+
122
+
123
+ def dp_to_tuple_eval(input_dict):
124
+ transform = build_transform("eval")
125
+ return (
126
+ transform(input_dict[".jpg"]),
127
+ input_dict[".label.cls"],
128
+ input_dict[".domain_label.cls"],
129
+ )
130
+
131
+
132
+ def load_dataset(domains: list[int], split: str):
133
+
134
+ laion_lister = FileLister("./data/laion400m_data", f"{split}*.tar")
135
+ genai_lister = {
136
+ d: FileLister(
137
+ f"./data/genai-images/{DOMAIN_LABELS[d]}",
138
+ f"{split}*.tar",
139
+ )
140
+ for d in domains
141
+ if DOMAIN_LABELS[d] != "laion"
142
+ }
143
+ weight_genai = 1 / len(genai_lister)
144
+
145
+ def open_lister(lister):
146
+ opener = FileOpener(lister, mode="b")
147
+ return opener.load_from_tar().routed_decode().webdataset()
148
+
149
+ buffer_size1 = 100 if split == "train" else 10
150
+ buffer_size2 = 100 if split == "train" else 10
151
+
152
+ if split != "train":
153
+ all_lister = [laion_lister] + list(genai_lister.values())
154
+ dp = open_lister(Concater(*all_lister)).sharding_filter()
155
+ else:
156
+ laion_dp = (
157
+ open_lister(laion_lister.shuffle())
158
+ .cycle()
159
+ .sharding_filter()
160
+ .shuffle(buffer_size=buffer_size1)
161
+ )
162
+ genai_dp = {
163
+ open_lister(genai_lister[d].shuffle())
164
+ .cycle()
165
+ .sharding_filter()
166
+ .shuffle(buffer_size=buffer_size1): weight_genai
167
+ for d in domains
168
+ if DOMAIN_LABELS[d] != "laion"
169
+ }
170
+ dp = SampleMultiplexer({laion_dp: 1, **genai_dp}).shuffle(
171
+ buffer_size=buffer_size2,
172
+ )
173
+
174
+ if split == "train":
175
+ dp = dp.map(dp_to_tuple_train)
176
+ else:
177
+ dp = dp.map(dp_to_tuple_eval)
178
+
179
+ return dp
180
+
181
+
182
+ def load_dataloader(
183
+ domains: list[int],
184
+ split: str,
185
+ batch_size: int = 32,
186
+ num_workers: int = 4,
187
+ ):
188
+ dp = load_dataset(domains, split)
189
+ # if split == "train":
190
+ # dp = UnderSamplerIterDataPipe(dp, {0: 0.5, 1: 0.5}, seed=42)
191
+ dp = dp.batch(batch_size).collate()
192
+ dl = DataLoader(
193
+ dp,
194
+ batch_size=None,
195
+ num_workers=num_workers,
196
+ pin_memory=True,
197
+ )
198
+
199
+ return dl
200
+
201
+
202
+ if __name__ == "__main__":
203
+ parser = argparse.ArgumentParser()
204
+
205
+ args = parser.parse_args()
206
+
207
+ # testing code
208
+ dl = load_dataloader([0, 1], "train", num_workers=8)
209
+ y_dist = collections.Counter()
210
+ d_dist = collections.Counter()
211
+
212
+ for i, (img, y, d) in tqdm(enumerate(dl)):
213
+ if i % 100 == 0:
214
+ print(y, d)
215
+ if i == 400:
216
+ break
217
+ y_dist.update(y.numpy())
218
+ d_dist.update(d.numpy())
219
+
220
+ print("class label")
221
+ for label in sorted(y_dist):
222
+ frequency = y_dist[label] / sum(y_dist.values())
223
+ print(f"• {label}: {frequency:.2%} ({y_dist[label]})")
224
+
225
+ print("domain label")
226
+ for label in sorted(d_dist):
227
+ frequency = d_dist[label] / sum(d_dist.values())
228
+ print(f"• {label}: {frequency:.2%} ({d_dist[label]})")
src/images/Diffusion/diffusion_data_loader.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import collections
3
+ import glob
4
+ import os
5
+ import random
6
+ from typing import Iterator
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import torchdata as td
14
+ import torchdata.datapipes as dp
15
+ from imwatermark import WatermarkEncoder
16
+ from PIL import (
17
+ Image,
18
+ ImageFile,
19
+ )
20
+ from torch.utils.data import (
21
+ DataLoader,
22
+ RandomSampler,
23
+ )
24
+ from torchdata.dataloader2 import (
25
+ DataLoader2,
26
+ MultiProcessingReadingService,
27
+ )
28
+ from torchdata.datapipes.iter import (
29
+ Concater,
30
+ FileLister,
31
+ FileOpener,
32
+ SampleMultiplexer,
33
+ )
34
+ from torchvision.transforms import v2
35
+ from tqdm import tqdm
36
+ from utils_sampling import UnderSamplerIterDataPipe
37
+
38
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
39
+ Image.MAX_IMAGE_PIXELS = 1000000000
40
+
41
+ encoder = WatermarkEncoder()
42
+ encoder.set_watermark("bytes", b"test")
43
+
44
+ DOMAIN_LABELS = {
45
+ 0: "laion",
46
+ 1: "StableDiffusion",
47
+ 2: "dalle2",
48
+ 3: "dalle3",
49
+ 4: "midjourney",
50
+ }
51
+
52
+ N_SAMPLES = {
53
+ 0: (115346, 14418, 14419),
54
+ 1: (22060, 2757, 2758),
55
+ 4: (21096, 2637, 2637),
56
+ 2: (13582, 1697, 1699),
57
+ 3: (12027, 1503, 1504),
58
+ }
59
+
60
+
61
+ @dp.functional_datapipe("collect_from_workers")
62
+ class WorkerResultCollector(dp.iter.IterDataPipe):
63
+ def __init__(self, source: dp.iter.IterDataPipe):
64
+ self.source = source
65
+
66
+ def __iter__(self) -> Iterator:
67
+ yield from self.source
68
+
69
+ def is_replicable(self) -> bool:
70
+ """Method to force data back to main process"""
71
+ return False
72
+
73
+
74
+ def crop_bottom(image, cutoff=16):
75
+ return image[:, :-cutoff, :]
76
+
77
+
78
+ def random_gaussian_blur(image, p=0.01):
79
+ if random.random() < p:
80
+ return v2.functional.gaussian_blur(image, kernel_size=5)
81
+ return image
82
+
83
+
84
+ def random_invisible_watermark(image, p=0.2):
85
+ image_np = np.array(image)
86
+ image_np = np.transpose(image_np, (1, 2, 0))
87
+
88
+ if image_np.ndim == 2: # Grayscale image
89
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2BGR)
90
+ elif image_np.shape[2] == 4: # RGBA image
91
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2BGR)
92
+
93
+ # print(image_np.shape)
94
+ if image_np.shape[0] < 256 or image_np.shape[1] < 256:
95
+ image_np = cv2.resize(
96
+ image_np, (256, 256), interpolation=cv2.INTER_AREA
97
+ )
98
+ if random.random() < p:
99
+ return encoder.encode(image_np, method="dwtDct")
100
+ return image_np
101
+
102
+
103
+ def build_transform(split: str):
104
+ train_transform = v2.Compose(
105
+ [
106
+ v2.Lambda(crop_bottom),
107
+ v2.RandomCrop((256, 256), pad_if_needed=True),
108
+ v2.Lambda(random_gaussian_blur),
109
+ v2.RandomGrayscale(p=0.05),
110
+ v2.Lambda(random_invisible_watermark),
111
+ v2.ToImage(),
112
+ ]
113
+ )
114
+
115
+ eval_transform = v2.Compose(
116
+ [
117
+ v2.CenterCrop((256, 256)),
118
+ ]
119
+ )
120
+ transform = train_transform if split == "train" else eval_transform
121
+
122
+ return transform
123
+
124
+
125
+ def dp_to_tuple_train(input_dict):
126
+ transform = build_transform("train")
127
+ return (
128
+ transform(input_dict[".jpg"]),
129
+ input_dict[".label.cls"],
130
+ input_dict[".domain_label.cls"],
131
+ )
132
+
133
+
134
+ def dp_to_tuple_eval(input_dict):
135
+ transform = build_transform("eval")
136
+ return (
137
+ transform(input_dict[".jpg"]),
138
+ input_dict[".label.cls"],
139
+ input_dict[".domain_label.cls"],
140
+ )
141
+
142
+
143
+ def load_dataset(domains: list[int], split: str):
144
+ laion_lister = FileLister("./data/laion400m_data", f"{split}*.tar")
145
+ genai_lister = {
146
+ d: FileLister(
147
+ f"./data/genai-images/{DOMAIN_LABELS[d]}", f"{split}*.tar"
148
+ )
149
+ for d in domains
150
+ if DOMAIN_LABELS[d] != "laion"
151
+ }
152
+ weight_genai = 1 / len(genai_lister)
153
+
154
+ def open_lister(lister):
155
+ opener = FileOpener(lister, mode="b")
156
+ return opener.load_from_tar().routed_decode().webdataset()
157
+
158
+ buffer_size1 = 100 if split == "train" else 10
159
+ buffer_size2 = 100 if split == "train" else 10
160
+
161
+ if split != "train":
162
+ all_lister = [laion_lister] + list(genai_lister.values())
163
+ dp = open_lister(Concater(*all_lister)).sharding_filter()
164
+ else:
165
+ laion_dp = (
166
+ open_lister(laion_lister.shuffle())
167
+ .cycle()
168
+ .sharding_filter()
169
+ .shuffle(buffer_size=buffer_size1)
170
+ )
171
+ genai_dp = {
172
+ open_lister(genai_lister[d].shuffle())
173
+ .cycle()
174
+ .sharding_filter()
175
+ .shuffle(
176
+ buffer_size=buffer_size1,
177
+ ): weight_genai
178
+ for d in domains
179
+ if DOMAIN_LABELS[d] != "laion"
180
+ }
181
+ dp = SampleMultiplexer({laion_dp: 1, **genai_dp}).shuffle(
182
+ buffer_size=buffer_size2
183
+ )
184
+
185
+ if split == "train":
186
+ dp = dp.map(dp_to_tuple_train)
187
+ else:
188
+ dp = dp.map(dp_to_tuple_eval)
189
+
190
+ return dp
191
+
192
+
193
+ def load_dataloader(
194
+ domains: list[int], split: str, batch_size: int = 32, num_workers: int = 4
195
+ ):
196
+ dp = load_dataset(domains, split)
197
+ # if split == "train":
198
+ # dp = UnderSamplerIterDataPipe(dp, {0: 0.5, 1: 0.5}, seed=42)
199
+ dp = dp.batch(batch_size).collate()
200
+ dl = DataLoader(
201
+ dp, batch_size=None, num_workers=num_workers, pin_memory=True
202
+ )
203
+
204
+ return dl
205
+
206
+
207
+ if __name__ == "__main__":
208
+ parser = argparse.ArgumentParser()
209
+
210
+ args = parser.parse_args()
211
+
212
+ # testing code
213
+ dl = load_dataloader([0, 1], "train", num_workers=8)
214
+ y_dist = collections.Counter()
215
+ d_dist = collections.Counter()
216
+
217
+ for i, (img, y, d) in tqdm(enumerate(dl)):
218
+ if i % 100 == 0:
219
+ print(y, d)
220
+ if i == 400:
221
+ break
222
+ y_dist.update(y.numpy())
223
+ d_dist.update(d.numpy())
224
+
225
+ print("class label")
226
+ for label in sorted(y_dist):
227
+ frequency = y_dist[label] / sum(y_dist.values())
228
+ print(f"• {label}: {frequency:.2%} ({y_dist[label]})")
229
+
230
+ print("domain label")
231
+ for label in sorted(d_dist):
232
+ frequency = d_dist[label] / sum(d_dist.values())
233
+ print(f"• {label}: {frequency:.2%} ({d_dist[label]})")
src/images/Diffusion/diffusion_model_classifier.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+
5
+ import pandas as pd
6
+ import pytorch_lightning as pl
7
+ import timm
8
+ import torch
9
+ import torchvision.transforms as transforms
10
+ from data_split import *
11
+ from dataloader import *
12
+ from PIL import Image
13
+ from pytorch_lightning.callbacks import (
14
+ EarlyStopping,
15
+ ModelCheckpoint,
16
+ )
17
+ from sklearn.metrics import roc_auc_score
18
+ from torchmetrics import (
19
+ Accuracy,
20
+ Recall,
21
+ )
22
+ from utils_sampling import *
23
+
24
+ logging.basicConfig(
25
+ filename="training.log", filemode="w", level=logging.INFO, force=True
26
+ )
27
+
28
+
29
+ class ImageClassifier(pl.LightningModule):
30
+ def __init__(self, lmd=0):
31
+ super().__init__()
32
+ self.model = timm.create_model(
33
+ "resnet50", pretrained=True, num_classes=1
34
+ )
35
+ self.accuracy = Accuracy(task="binary", threshold=0.5)
36
+ self.recall = Recall(task="binary", threshold=0.5)
37
+ self.validation_outputs = []
38
+ self.lmd = lmd
39
+
40
+ def forward(self, x):
41
+ return self.model(x)
42
+
43
+ def training_step(self, batch):
44
+ images, labels, _ = batch
45
+ outputs = self.forward(images).squeeze()
46
+
47
+ print(f"Shape of outputs (training): {outputs.shape}")
48
+ print(f"Shape of labels (training): {labels.shape}")
49
+
50
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
51
+ logging.info(f"Training Step - ERM loss: {loss.item()}")
52
+ loss += self.lmd * (outputs**2).mean() # SD loss penalty
53
+ logging.info(f"Training Step - SD loss: {loss.item()}")
54
+ return loss
55
+
56
+ def validation_step(self, batch):
57
+ images, labels, _ = batch
58
+ outputs = self.forward(images).squeeze()
59
+
60
+ if outputs.shape == torch.Size([]):
61
+ return
62
+
63
+ print(f"Shape of outputs (validation): {outputs.shape}")
64
+ print(f"Shape of labels (validation): {labels.shape}")
65
+
66
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
67
+ preds = torch.sigmoid(outputs)
68
+ self.log("val_loss", loss, prog_bar=True, sync_dist=True)
69
+ self.log(
70
+ "val_acc",
71
+ self.accuracy(preds, labels.int()),
72
+ prog_bar=True,
73
+ sync_dist=True,
74
+ )
75
+ self.log(
76
+ "val_recall",
77
+ self.recall(preds, labels.int()),
78
+ prog_bar=True,
79
+ sync_dist=True,
80
+ )
81
+ output = {"val_loss": loss, "preds": preds, "labels": labels}
82
+ self.validation_outputs.append(output)
83
+ logging.info(f"Validation Step - Batch loss: {loss.item()}")
84
+ return output
85
+
86
+ def predict_step(self, batch):
87
+ images, label, domain = batch
88
+ outputs = self.forward(images).squeeze()
89
+ preds = torch.sigmoid(outputs)
90
+ return preds, label, domain
91
+
92
+ def on_validation_epoch_end(self):
93
+ if not self.validation_outputs:
94
+ logging.warning("No outputs in validation step to process")
95
+ return
96
+ preds = torch.cat([x["preds"] for x in self.validation_outputs])
97
+ labels = torch.cat([x["labels"] for x in self.validation_outputs])
98
+ if labels.unique().size(0) == 1:
99
+ logging.warning("Only one class in validation step")
100
+ return
101
+ auc_score = roc_auc_score(labels.cpu(), preds.cpu())
102
+ self.log("val_auc", auc_score, prog_bar=True, sync_dist=True)
103
+ logging.info(f"Validation Epoch End - AUC score: {auc_score}")
104
+ self.validation_outputs = []
105
+
106
+ def configure_optimizers(self):
107
+ optimizer = torch.optim.Adam(self.model.parameters(), lr=0.0005)
108
+ return optimizer
109
+
110
+
111
+ checkpoint_callback = ModelCheckpoint(
112
+ monitor="val_loss",
113
+ dirpath="./model_checkpoints/",
114
+ filename="image-classifier-{step}-{val_loss:.2f}",
115
+ save_top_k=3,
116
+ mode="min",
117
+ every_n_train_steps=1001,
118
+ enable_version_counter=True,
119
+ )
120
+
121
+ early_stop_callback = EarlyStopping(
122
+ monitor="val_loss",
123
+ patience=4,
124
+ mode="min",
125
+ )
126
+
127
+
128
+ def load_image(image_path, transform=None):
129
+ image = Image.open(image_path).convert("RGB")
130
+
131
+ if transform:
132
+ image = transform(image)
133
+
134
+ return image
135
+
136
+
137
+ def predict_single_image(image_path, model, transform=None):
138
+ image = load_image(image_path, transform)
139
+
140
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
141
+
142
+ model.to(device)
143
+
144
+ image = image.to(device)
145
+
146
+ model.eval()
147
+
148
+ with torch.no_grad():
149
+ image = image.unsqueeze(0)
150
+ output = model(image).squeeze()
151
+ print(output)
152
+ prediction = torch.sigmoid(output).item()
153
+
154
+ return prediction
155
+
156
+
157
+ parser = argparse.ArgumentParser()
158
+ parser.add_argument(
159
+ "--ckpt_path", help="checkpoint to continue from", required=False
160
+ )
161
+ parser.add_argument(
162
+ "--predict", help="predict on test set", action="store_true"
163
+ )
164
+ parser.add_argument("--reset", help="reset training", action="store_true")
165
+ parser.add_argument(
166
+ "--predict_image",
167
+ help="predict the class of a single image",
168
+ action="store_true",
169
+ )
170
+ parser.add_argument(
171
+ "--image_path",
172
+ help="path to the image to predict",
173
+ type=str,
174
+ required=False,
175
+ )
176
+ args = parser.parse_args()
177
+
178
+ train_domains = [0, 1, 4]
179
+ val_domains = [0, 1, 4]
180
+ lmd_value = 0
181
+
182
+ if args.predict:
183
+ test_dl = load_dataloader(
184
+ [0, 1, 2, 3, 4], "test", batch_size=128, num_workers=1
185
+ )
186
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
187
+ trainer = pl.Trainer()
188
+ predictions = trainer.predict(model, dataloaders=test_dl)
189
+ preds, labels, domains = zip(*predictions)
190
+ preds = torch.cat(preds).cpu().numpy()
191
+ labels = torch.cat(labels).cpu().numpy()
192
+ domains = torch.cat(domains).cpu().numpy()
193
+ print(preds.shape, labels.shape, domains.shape)
194
+ df = pd.DataFrame({"preds": preds, "labels": labels, "domains": domains})
195
+ filename = "preds-" + args.ckpt_path.split("/")[-1]
196
+ df.to_csv(f"outputs/{filename}.csv", index=False)
197
+ elif args.predict_image:
198
+ image_path = args.image_path
199
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
200
+
201
+ # Define the transformations for the image
202
+ transform = transforms.Compose(
203
+ [
204
+ transforms.Resize((224, 224)), # Image size expected by ResNet50
205
+ transforms.ToTensor(),
206
+ transforms.Normalize(
207
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
208
+ ),
209
+ ]
210
+ )
211
+
212
+ prediction = predict_single_image(image_path, model, transform)
213
+ print("prediction", prediction)
214
+
215
+ # Output the prediction
216
+ print(
217
+ f"Prediction for {image_path}: {'Human' if prediction <= 0.001 else 'Generated'}"
218
+ )
219
+ else:
220
+ train_dl = load_dataloader(
221
+ train_domains, "train", batch_size=128, num_workers=4
222
+ )
223
+ logging.info("Training dataloader loaded")
224
+ val_dl = load_dataloader(val_domains, "val", batch_size=128, num_workers=4)
225
+ logging.info("Validation dataloader loaded")
226
+
227
+ if args.reset:
228
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
229
+ else:
230
+ model = ImageClassifier(lmd=lmd_value)
231
+ trainer = pl.Trainer(
232
+ callbacks=[checkpoint_callback, early_stop_callback],
233
+ max_steps=20000,
234
+ val_check_interval=1000,
235
+ check_val_every_n_epoch=None,
236
+ )
237
+ trainer.fit(
238
+ model=model,
239
+ train_dataloaders=train_dl,
240
+ val_dataloaders=val_dl,
241
+ ckpt_path=args.ckpt_path if not args.reset else None,
242
+ )
src/images/Diffusion/evaluation.ipynb ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import pandas as pd\n",
10
+ "import numpy as np\n",
11
+ "import polars as pl\n",
12
+ "import matplotlib.pyplot as plt\n",
13
+ "import seaborn as sns\n",
14
+ "from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score, f1_score, RocCurveDisplay\n",
15
+ "\n",
16
+ "sns.set()"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": null,
22
+ "metadata": {},
23
+ "outputs": [],
24
+ "source": [
25
+ "def pfbeta(labels, predictions, beta=1):\n",
26
+ " y_true_count = 0\n",
27
+ " ctp = 0\n",
28
+ " cfp = 0\n",
29
+ "\n",
30
+ " for idx in range(len(labels)):\n",
31
+ " prediction = min(max(predictions[idx], 0), 1)\n",
32
+ " if (labels[idx]):\n",
33
+ " y_true_count += 1\n",
34
+ " ctp += prediction\n",
35
+ " else:\n",
36
+ " cfp += prediction\n",
37
+ "\n",
38
+ " beta_squared = beta * beta\n",
39
+ " c_precision = ctp / (ctp + cfp)\n",
40
+ " c_recall = ctp / y_true_count\n",
41
+ " if (c_precision > 0 and c_recall > 0):\n",
42
+ " result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall)\n",
43
+ " return result\n",
44
+ " else:\n",
45
+ " return 0"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "execution_count": null,
51
+ "metadata": {},
52
+ "outputs": [],
53
+ "source": [
54
+ "def get_part_metrics(df: pl.DataFrame, threshold=0.3) -> dict:\n",
55
+ " df = df.with_columns((df[\"preds\"] > threshold).alias(\"preds_bin\"))\n",
56
+ " metrics = {}\n",
57
+ " # binary metrics using the threshold\n",
58
+ " metrics[\"accuracy\"] = accuracy_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
59
+ " metrics[\"precision\"] = precision_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
60
+ " metrics[\"recall\"] = recall_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
61
+ " metrics[\"f1\"] = f1_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
62
+ " # probabilistic F1 (doesn't depend on the threshold)\n",
63
+ " metrics[\"pf1\"] = pfbeta(df[\"labels\"].to_numpy(), df[\"preds\"].to_numpy())\n",
64
+ " # ROC AUC\n",
65
+ " metrics[\"roc_auc\"] = roc_auc_score(df[\"labels\"].to_numpy(), df[\"preds\"].to_numpy())\n",
66
+ " return metrics\n",
67
+ "\n",
68
+ "\n",
69
+ "def get_all_metrics(df: pl.DataFrame, threshold=0.3) -> pd.DataFrame:\n",
70
+ " groups = [list(range(5)), [0, 1], [0, 4], [0, 2], [0, 3]]\n",
71
+ " group_names = [\"all\", \"StableDiffusion\", \"Midjourney\", \"Dalle2\", \"Dalle3\"]\n",
72
+ " all_metrics = []\n",
73
+ " for i, g in enumerate(groups):\n",
74
+ " subset = df.filter(pl.col(\"domains\").is_in(g))\n",
75
+ " metrics = get_part_metrics(subset, threshold=threshold)\n",
76
+ " metrics[\"group\"] = group_names[i]\n",
77
+ " all_metrics.append(metrics)\n",
78
+ " \n",
79
+ " return pd.DataFrame(all_metrics)"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "df1 = pl.read_csv(\"outputs/preds-image-classifier-1.csv\")\n",
89
+ "metrics_df1 = get_all_metrics(df1, threshold=0.5)"
90
+ ]
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "execution_count": null,
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "metrics_df1"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": null,
104
+ "metadata": {},
105
+ "outputs": [],
106
+ "source": [
107
+ "df14 = pl.read_csv(\"outputs/preds-image-classifier-14.csv\")\n",
108
+ "metrics_df14 = get_all_metrics(df14, threshold=0.5)"
109
+ ]
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "execution_count": null,
114
+ "metadata": {},
115
+ "outputs": [],
116
+ "source": [
117
+ "metrics_df14"
118
+ ]
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "execution_count": null,
123
+ "metadata": {},
124
+ "outputs": [],
125
+ "source": [
126
+ "df142 = pl.read_csv(\"outputs/preds-image-classifier-142.csv\")\n",
127
+ "metrics_df142 = get_all_metrics(df142, threshold=0.5)"
128
+ ]
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "execution_count": null,
133
+ "metadata": {},
134
+ "outputs": [],
135
+ "source": [
136
+ "metrics_df142"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "execution_count": null,
142
+ "metadata": {},
143
+ "outputs": [],
144
+ "source": [
145
+ "df1423 = pl.read_csv(\"outputs/preds-image-classifier-1423.csv\")\n",
146
+ "metrics_df1423 = get_all_metrics(df1423, threshold=0.5)"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "execution_count": null,
152
+ "metadata": {},
153
+ "outputs": [],
154
+ "source": [
155
+ "metrics_df1423"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "execution_count": null,
161
+ "metadata": {},
162
+ "outputs": [],
163
+ "source": []
164
+ }
165
+ ],
166
+ "metadata": {
167
+ "kernelspec": {
168
+ "display_name": "GenAI-image-detection-Z_9oJJe7",
169
+ "language": "python",
170
+ "name": "python3"
171
+ },
172
+ "language_info": {
173
+ "codemirror_mode": {
174
+ "name": "ipython",
175
+ "version": 3
176
+ },
177
+ "file_extension": ".py",
178
+ "mimetype": "text/x-python",
179
+ "name": "python",
180
+ "nbconvert_exporter": "python",
181
+ "pygments_lexer": "ipython3",
182
+ "version": "3.11.6"
183
+ }
184
+ },
185
+ "nbformat": 4,
186
+ "nbformat_minor": 2
187
+ }
src/images/Diffusion/model.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+
5
+ import pandas as pd
6
+ import pytorch_lightning as pl
7
+ import timm
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torchvision.transforms as transforms
11
+ from dataloader import load_dataloader
12
+ from PIL import Image
13
+ from pytorch_lightning.callbacks import (
14
+ EarlyStopping,
15
+ ModelCheckpoint,
16
+ )
17
+ from sklearn.metrics import roc_auc_score
18
+ from torchmetrics import (
19
+ Accuracy,
20
+ Recall,
21
+ )
22
+
23
+ logging.basicConfig(
24
+ filename="training.log",
25
+ filemode="w",
26
+ level=logging.INFO,
27
+ force=True,
28
+ )
29
+
30
+
31
+ class ImageClassifier(pl.LightningModule):
32
+ def __init__(self, lmd=0):
33
+ super().__init__()
34
+ self.model = timm.create_model(
35
+ "resnet50",
36
+ pretrained=True,
37
+ num_classes=1,
38
+ )
39
+ self.accuracy = Accuracy(task="binary", threshold=0.5)
40
+ self.recall = Recall(task="binary", threshold=0.5)
41
+ self.validation_outputs = []
42
+ self.lmd = lmd
43
+
44
+ def forward(self, x):
45
+ return self.model(x)
46
+
47
+ def training_step(self, batch):
48
+ images, labels, _ = batch
49
+ outputs = self.forward(images).squeeze()
50
+
51
+ print(f"Shape of outputs (training): {outputs.shape}")
52
+ print(f"Shape of labels (training): {labels.shape}")
53
+
54
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
55
+ logging.info(f"Training Step - ERM loss: {loss.item()}")
56
+ loss += self.lmd * (outputs**2).mean() # SD loss penalty
57
+ logging.info(f"Training Step - SD loss: {loss.item()}")
58
+ return loss
59
+
60
+ def validation_step(self, batch):
61
+ images, labels, _ = batch
62
+ outputs = self.forward(images).squeeze()
63
+
64
+ if outputs.shape == torch.Size([]):
65
+ return
66
+
67
+ print(f"Shape of outputs (validation): {outputs.shape}")
68
+ print(f"Shape of labels (validation): {labels.shape}")
69
+
70
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
71
+ preds = torch.sigmoid(outputs)
72
+ self.log("val_loss", loss, prog_bar=True, sync_dist=True)
73
+ self.log(
74
+ "val_acc",
75
+ self.accuracy(preds, labels.int()),
76
+ prog_bar=True,
77
+ sync_dist=True,
78
+ )
79
+ self.log(
80
+ "val_recall",
81
+ self.recall(preds, labels.int()),
82
+ prog_bar=True,
83
+ sync_dist=True,
84
+ )
85
+ output = {"val_loss": loss, "preds": preds, "labels": labels}
86
+ self.validation_outputs.append(output)
87
+ logging.info(f"Validation Step - Batch loss: {loss.item()}")
88
+ return output
89
+
90
+ def predict_step(self, batch):
91
+ images, label, domain = batch
92
+ outputs = self.forward(images).squeeze()
93
+ preds = torch.sigmoid(outputs)
94
+ return preds, label, domain
95
+
96
+ def on_validation_epoch_end(self):
97
+ if not self.validation_outputs:
98
+ logging.warning("No outputs in validation step to process")
99
+ return
100
+ preds = torch.cat([x["preds"] for x in self.validation_outputs])
101
+ labels = torch.cat([x["labels"] for x in self.validation_outputs])
102
+ if labels.unique().size(0) == 1:
103
+ logging.warning("Only one class in validation step")
104
+ return
105
+ auc_score = roc_auc_score(labels.cpu(), preds.cpu())
106
+ self.log("val_auc", auc_score, prog_bar=True, sync_dist=True)
107
+ logging.info(f"Validation Epoch End - AUC score: {auc_score}")
108
+ self.validation_outputs = []
109
+
110
+ def configure_optimizers(self):
111
+ optimizer = torch.optim.Adam(self.model.parameters(), lr=0.0005)
112
+ return optimizer
113
+
114
+
115
+ checkpoint_callback = ModelCheckpoint(
116
+ monitor="val_loss",
117
+ dirpath="./model_checkpoints/",
118
+ filename="image-classifier-{step}-{val_loss:.2f}",
119
+ save_top_k=3,
120
+ mode="min",
121
+ every_n_train_steps=1001,
122
+ enable_version_counter=True,
123
+ )
124
+
125
+ early_stop_callback = EarlyStopping(
126
+ monitor="val_loss",
127
+ patience=4,
128
+ mode="min",
129
+ )
130
+
131
+
132
+ def load_image(image_path, transform=None):
133
+ image = Image.open(image_path).convert("RGB")
134
+
135
+ if transform:
136
+ image = transform(image)
137
+
138
+ return image
139
+
140
+
141
+ def predict_single_image(image_path, model, transform=None):
142
+ image = load_image(image_path, transform)
143
+
144
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
145
+
146
+ model.to(device)
147
+
148
+ image = image.to(device)
149
+
150
+ model.eval()
151
+
152
+ with torch.no_grad():
153
+ image = image.unsqueeze(0)
154
+ output = model(image).squeeze()
155
+ print(output)
156
+ prediction = torch.sigmoid(output).item()
157
+
158
+ return prediction
159
+
160
+
161
+ parser = argparse.ArgumentParser()
162
+ parser.add_argument(
163
+ "--ckpt_path",
164
+ help="checkpoint to continue from",
165
+ required=False,
166
+ )
167
+ parser.add_argument(
168
+ "--predict",
169
+ help="predict on test set",
170
+ action="store_true",
171
+ )
172
+ parser.add_argument("--reset", help="reset training", action="store_true")
173
+ parser.add_argument(
174
+ "--predict_image",
175
+ help="predict the class of a single image",
176
+ action="store_true",
177
+ )
178
+ parser.add_argument(
179
+ "--image_path",
180
+ help="path to the image to predict",
181
+ type=str,
182
+ required=False,
183
+ )
184
+ parser.add_argument(
185
+ "--dir",
186
+ help="path to the images to predict",
187
+ type=str,
188
+ required=False,
189
+ )
190
+ parser.add_argument(
191
+ "--output_file",
192
+ help="path to output file",
193
+ type=str,
194
+ required=False,
195
+ )
196
+ args = parser.parse_args()
197
+
198
+ train_domains = [0, 1, 4]
199
+ val_domains = [0, 1, 4]
200
+ lmd_value = 0
201
+
202
+ if args.predict:
203
+ test_dl = load_dataloader(
204
+ [0, 1, 2, 3, 4],
205
+ "test",
206
+ batch_size=128,
207
+ num_workers=1,
208
+ )
209
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
210
+ trainer = pl.Trainer()
211
+ predictions = trainer.predict(model, dataloaders=test_dl)
212
+ preds, labels, domains = zip(*predictions)
213
+ preds = torch.cat(preds).cpu().numpy()
214
+ labels = torch.cat(labels).cpu().numpy()
215
+ domains = torch.cat(domains).cpu().numpy()
216
+ print(preds.shape, labels.shape, domains.shape)
217
+ df = pd.DataFrame({"preds": preds, "labels": labels, "domains": domains})
218
+ filename = "preds-" + args.ckpt_path.split("/")[-1]
219
+ df.to_csv(f"outputs/{filename}.csv", index=False)
220
+ elif args.predict_image:
221
+ image_path = args.image_path
222
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
223
+
224
+ # Define the transformations for the image
225
+ # transform = transforms.Compose(
226
+ # [
227
+ # transforms.Resize((224, 224)), # Image size expected by ResNet50
228
+ # transforms.ToTensor(),
229
+ # transforms.Normalize(
230
+ # mean=[0.485, 0.456, 0.406],
231
+ # std=[0.229, 0.224, 0.225],
232
+ # ),
233
+ # ],
234
+ # )
235
+
236
+ transform = transforms.Compose(
237
+ [
238
+ transforms.CenterCrop((256, 256)),
239
+ transforms.ToTensor(),
240
+ ],
241
+ )
242
+
243
+ prediction = predict_single_image(image_path, model, transform)
244
+ print("prediction", prediction)
245
+
246
+ # Output the prediction
247
+ print(
248
+ f"Prediction for {image_path}: "
249
+ f"{'Human' if prediction <= 0.001 else 'Generated'}",
250
+ )
251
+ elif args.dir is not None:
252
+ predictions = []
253
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
254
+ # Define the transformations for the image
255
+ # transform = transforms.Compose(
256
+ # [
257
+ # transforms.Resize((224, 224)), # Image size expected by ResNet50
258
+ # transforms.ToTensor(),
259
+ # transforms.Normalize(
260
+ # mean=[0.485, 0.456, 0.406],
261
+ # std=[0.229, 0.224, 0.225],
262
+ # ),
263
+ # ],
264
+ # )
265
+ transform = transforms.Compose(
266
+ [
267
+ transforms.CenterCrop((256, 256)),
268
+ transforms.ToTensor(),
269
+ ],
270
+ )
271
+ for root, dirs, files in os.walk(os.path.abspath(args.dir)):
272
+ for f_name in files:
273
+ f = os.path.join(root, f_name)
274
+ print(f"Predicting: {f}")
275
+ p = predict_single_image(f, model, transform)
276
+ predictions.append([f, f.split("/")[-2], p, p > 0.5])
277
+ print(f"--predicted: {p}")
278
+
279
+ df = pd.DataFrame(predictions, columns=["path", "folder", "pred", "class"])
280
+ df.to_csv(args.output_file, index=False)
281
+ else:
282
+ train_dl = load_dataloader(
283
+ train_domains,
284
+ "train",
285
+ batch_size=128,
286
+ num_workers=4,
287
+ )
288
+ logging.info("Training dataloader loaded")
289
+ val_dl = load_dataloader(val_domains, "val", batch_size=128, num_workers=4)
290
+ logging.info("Validation dataloader loaded")
291
+
292
+ if args.reset:
293
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
294
+ else:
295
+ model = ImageClassifier(lmd=lmd_value)
296
+ trainer = pl.Trainer(
297
+ callbacks=[checkpoint_callback, early_stop_callback],
298
+ max_steps=20000,
299
+ val_check_interval=1000,
300
+ check_val_every_n_epoch=None,
301
+ )
302
+ trainer.fit(
303
+ model=model,
304
+ train_dataloaders=train_dl,
305
+ val_dataloaders=val_dl,
306
+ ckpt_path=args.ckpt_path if not args.reset else None,
307
+ )
src/images/Diffusion/sample_laion_script.ipynb ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import dask.dataframe as dd\n",
10
+ "from dask.diagnostics import ProgressBar\n",
11
+ "import os\n",
12
+ "\n",
13
+ "directory_path = '/Users/fionachow/Documents/NYU/CDS/Fall 2023/CSCI - GA 2271 - Computer Vision/Project/'\n",
14
+ "\n",
15
+ "file_prefix = 'part'\n",
16
+ "\n",
17
+ "def list_files_with_prefix(directory, prefix):\n",
18
+ " file_paths = []\n",
19
+ "\n",
20
+ " for root, _, files in os.walk(directory):\n",
21
+ " for file in files:\n",
22
+ " if file.startswith(prefix):\n",
23
+ " absolute_path = os.path.join(root, file)\n",
24
+ " file_paths.append(absolute_path)\n",
25
+ "\n",
26
+ " return file_paths\n",
27
+ "\n",
28
+ "laion_file_paths = list_files_with_prefix(directory_path, file_prefix)\n",
29
+ "\n",
30
+ "dataframes = [dd.read_parquet(file) for file in laion_file_paths]\n",
31
+ "combined_dataframe = dd.multi.concat(dataframes)\n",
32
+ "\n",
33
+ "with ProgressBar():\n",
34
+ " row_count = combined_dataframe.shape[0].compute()\n",
35
+ " print(row_count)\n",
36
+ "\n",
37
+ "filtered_df = combined_dataframe[combined_dataframe['NSFW'] == \"UNLIKELY\"]\n",
38
+ "\n",
39
+ "num_samples = 225_000\n",
40
+ "selected_rows = filtered_df.sample(frac=num_samples / filtered_df.shape[0].compute())\n",
41
+ "\n",
42
+ "with ProgressBar():\n",
43
+ " sampled_rows = selected_rows.compute()\n",
44
+ "\n",
45
+ "print(len(sampled_rows))\n",
46
+ "\n",
47
+ "with ProgressBar():\n",
48
+ " selected_rows.to_parquet('laion_sampled', write_index=False)\n"
49
+ ]
50
+ }
51
+ ],
52
+ "metadata": {
53
+ "kernelspec": {
54
+ "display_name": "bloom",
55
+ "language": "python",
56
+ "name": "python3"
57
+ },
58
+ "language_info": {
59
+ "codemirror_mode": {
60
+ "name": "ipython",
61
+ "version": 3
62
+ },
63
+ "file_extension": ".py",
64
+ "mimetype": "text/x-python",
65
+ "name": "python",
66
+ "nbconvert_exporter": "python",
67
+ "pygments_lexer": "ipython3",
68
+ "version": "3.9.16"
69
+ }
70
+ },
71
+ "nbformat": 4,
72
+ "nbformat_minor": 2
73
+ }
src/images/Diffusion/scrape.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import time
3
+
4
+ import polars as pl
5
+ import requests
6
+
7
+
8
+ def call_api(param):
9
+ url = "https://api.pullpush.io/reddit/search/submission/"
10
+ response = requests.get(url, params=param)
11
+ json_data = response.json()["data"]
12
+ create_utc = []
13
+ media_id = []
14
+ media_type_ls = []
15
+ post_ids = []
16
+ post_titles = []
17
+ cur_utc = 0
18
+ for submission in json_data:
19
+ cur_flair = submission["link_flair_text"]
20
+ cur_utc = submission["created_utc"]
21
+ media_ls = (
22
+ submission["media_metadata"]
23
+ if "media_metadata" in submission.keys()
24
+ else None
25
+ )
26
+ if param["flair"] is not None and cur_flair != param["flair"]:
27
+ continue
28
+ if media_ls is None:
29
+ continue
30
+ for id in media_ls.keys():
31
+ if media_ls[id]["status"] != "valid":
32
+ continue
33
+ try:
34
+ media_type = media_ls[id]["m"]
35
+ except: # noqa
36
+ # video will error out
37
+ continue
38
+ if media_type == "image/png":
39
+ media_type_ls.append("png")
40
+ elif media_type == "image/jpg":
41
+ media_type_ls.append("jpg")
42
+ else:
43
+ continue
44
+ create_utc.append(int(cur_utc))
45
+ post_ids.append(submission["id"])
46
+ post_titles.append(submission["title"])
47
+ media_id.append(id)
48
+
49
+ df = pl.DataFrame(
50
+ {
51
+ "create_utc": create_utc,
52
+ "media_id": media_id,
53
+ "media_type": media_type_ls,
54
+ "post_id": post_ids,
55
+ "post_title": post_titles,
56
+ },
57
+ schema={
58
+ "create_utc": pl.Int64,
59
+ "media_id": pl.Utf8,
60
+ "media_type": pl.Utf8,
61
+ "post_id": pl.Utf8,
62
+ "post_title": pl.Utf8,
63
+ },
64
+ )
65
+ return df, int(cur_utc)
66
+
67
+
68
+ def scraping_loop(
69
+ subreddit,
70
+ flair,
71
+ max_num=30000,
72
+ output_name=None,
73
+ before=None,
74
+ ):
75
+ collected_all = []
76
+ collected_len = 0
77
+ last_timestamp = int(time.time()) if before is None else before
78
+ param = {
79
+ "subreddit": subreddit,
80
+ "flair": flair,
81
+ "before": last_timestamp,
82
+ }
83
+ while collected_len < max_num:
84
+ collected_df, last_timestamp = call_api(param)
85
+ if collected_df.shape[0] == 0:
86
+ print("No more data, saving current data and exiting...")
87
+ break
88
+ collected_all.append(collected_df)
89
+ collected_len += collected_df.shape[0]
90
+ print(
91
+ f"collected_len: {collected_len}, "
92
+ f"last_timestamp: {last_timestamp}",
93
+ )
94
+ param["before"] = last_timestamp
95
+
96
+ df = pl.concat(collected_all)
97
+ df = (
98
+ df.with_columns(
99
+ pl.col("media_id")
100
+ .str.replace(r"^", "https://i.redd.it/")
101
+ .alias("url1"),
102
+ pl.col("create_utc")
103
+ .cast(pl.Int64)
104
+ .cast(pl.Utf8)
105
+ .str.to_datetime("%s")
106
+ .alias("time"),
107
+ )
108
+ .with_columns(
109
+ pl.col("media_type").str.replace(r"^", ".").alias("url2"),
110
+ )
111
+ .with_columns(
112
+ pl.concat_str(
113
+ [pl.col("url1"), pl.col("url2")],
114
+ separator="",
115
+ ).alias("url"),
116
+ )
117
+ .select("time", "url", "post_id", "post_title")
118
+ )
119
+ if output_name is None:
120
+ output_name = subreddit
121
+ df.write_parquet(f"urls/{output_name}.parquet")
122
+ df.select("url").write_csv(f"urls/{output_name}.csv", has_header=False)
123
+
124
+
125
+ if __name__ == "__main__":
126
+ parser = argparse.ArgumentParser()
127
+ parser.add_argument("--subreddit", help="subreddit name")
128
+ parser.add_argument("--flair", help="flair filter", default=None, type=str)
129
+ parser.add_argument(
130
+ "--max_num",
131
+ help="max number of posts to scrape",
132
+ default=30000,
133
+ type=int,
134
+ )
135
+ parser.add_argument(
136
+ "--output_name",
137
+ help="custom output name",
138
+ default=None,
139
+ )
140
+ parser.add_argument(
141
+ "--before",
142
+ help="before timestamp",
143
+ default=None,
144
+ type=int,
145
+ )
146
+
147
+ args = parser.parse_args()
148
+
149
+ scraping_loop(**args.__dict__)
src/images/Diffusion/utils_sampling.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import random
3
+ from typing import Callable
4
+
5
+ from torchdata.datapipes.iter import IterDataPipe
6
+
7
+
8
+ def get_second_entry(sample):
9
+ return sample[1]
10
+
11
+
12
+ class UnderSamplerIterDataPipe(IterDataPipe):
13
+ """Dataset wrapper for under-sampling.
14
+
15
+ Copied from: https://github.com/MaxHalford/pytorch-resample/blob/master/pytorch_resample/under.py # noqa
16
+ Modified to work with multiple labels.
17
+
18
+ MIT License
19
+
20
+ Copyright (c) 2020 Max Halford
21
+
22
+ This method is based on rejection sampling.
23
+
24
+ Parameters:
25
+ dataset
26
+ desired_dist: The desired class distribution.
27
+ The keys are the classes whilst the
28
+ values are the desired class percentages.
29
+ The values are normalised so that sum up
30
+ to 1.
31
+ label_getter: A function that takes a sample and returns its label.
32
+ seed: Random seed for reproducibility.
33
+
34
+ Attributes:
35
+ actual_dist: The counts of the observed sample labels.
36
+ rng: A random number generator instance.
37
+
38
+ References:
39
+ - https://www.wikiwand.com/en/Rejection_sampling
40
+
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ dataset: IterDataPipe,
46
+ desired_dist: dict,
47
+ label_getter: Callable = get_second_entry,
48
+ seed: int = None,
49
+ ):
50
+
51
+ self.dataset = dataset
52
+ self.desired_dist = {
53
+ c: p / sum(desired_dist.values()) for c, p in desired_dist.items()
54
+ }
55
+ self.label_getter = label_getter
56
+ self.seed = seed
57
+
58
+ self.actual_dist = collections.Counter()
59
+ self.rng = random.Random(seed)
60
+ self._pivot = None
61
+
62
+ def __iter__(self):
63
+
64
+ for dp in self.dataset:
65
+ y = self.label_getter(dp)
66
+
67
+ self.actual_dist[y] += 1
68
+
69
+ # To ease notation
70
+ f = self.desired_dist
71
+ g = self.actual_dist
72
+
73
+ # Check if the pivot needs to be changed
74
+ if y != self._pivot:
75
+ self._pivot = max(g.keys(), key=lambda y: f[y] / g[y])
76
+ else:
77
+ yield dp
78
+ continue
79
+
80
+ # Determine the sampling ratio if the observed label
81
+ # is not the pivot
82
+ M = f[self._pivot] / g[self._pivot]
83
+ ratio = f[y] / (M * g[y])
84
+
85
+ if ratio < 1 and self.rng.random() < ratio:
86
+ yield dp
87
+
88
+ @classmethod
89
+ def expected_size(cls, n, desired_dist, actual_dist):
90
+ M = max(
91
+ desired_dist.get(k) / actual_dist.get(k)
92
+ for k in set(desired_dist) | set(actual_dist)
93
+ )
94
+ return int(n / M)
src/images/Diffusion/visualizations.ipynb ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "%pip install polars-lts-cpu"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "import pandas as pd\n",
19
+ "import numpy as np\n",
20
+ "import polars as pl\n",
21
+ "import matplotlib.pyplot as plt\n",
22
+ "import seaborn as sns\n",
23
+ "from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score, f1_score"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "def pfbeta(labels, predictions, beta=1):\n",
33
+ " y_true_count = 0\n",
34
+ " ctp = 0\n",
35
+ " cfp = 0\n",
36
+ "\n",
37
+ " for idx in range(len(labels)):\n",
38
+ " prediction = min(max(predictions[idx], 0), 1)\n",
39
+ " if (labels[idx]):\n",
40
+ " y_true_count += 1\n",
41
+ " ctp += prediction\n",
42
+ " else:\n",
43
+ " cfp += prediction\n",
44
+ "\n",
45
+ " beta_squared = beta * beta\n",
46
+ " c_precision = ctp / (ctp + cfp)\n",
47
+ " c_recall = ctp / y_true_count\n",
48
+ " if (c_precision > 0 and c_recall > 0):\n",
49
+ " result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall)\n",
50
+ " return result\n",
51
+ " else:\n",
52
+ " return 0\n",
53
+ "\n",
54
+ "def get_part_metrics(df: pl.DataFrame, threshold=0.3) -> dict:\n",
55
+ " df = df.with_columns((df[\"preds\"] > threshold).alias(\"preds_bin\"))\n",
56
+ " metrics = {}\n",
57
+ " # binary metrics using the threshold\n",
58
+ " metrics[\"accuracy\"] = accuracy_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
59
+ " metrics[\"precision\"] = precision_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
60
+ " metrics[\"recall\"] = recall_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
61
+ " metrics[\"f1\"] = f1_score(df[\"labels\"].to_numpy(), df[\"preds_bin\"].to_numpy())\n",
62
+ " # probabilistic F1 (doesn't depend on the threshold)\n",
63
+ " metrics[\"pf1\"] = pfbeta(df[\"labels\"].to_numpy(), df[\"preds\"].to_numpy())\n",
64
+ " # ROC AUC\n",
65
+ " metrics[\"roc_auc\"] = roc_auc_score(df[\"labels\"].to_numpy(), df[\"preds\"].to_numpy())\n",
66
+ " return metrics\n",
67
+ "\n",
68
+ "\n",
69
+ "def get_all_metrics(df: pl.DataFrame, threshold=0.3) -> pd.DataFrame:\n",
70
+ " groups = [list(range(5)), [0, 1], [0, 4], [0, 2], [0, 3]]\n",
71
+ " group_names = [\"all\", \"StableDiffusion\", \"Midjourney\", \"Dalle2\", \"Dalle3\"]\n",
72
+ " all_metrics = []\n",
73
+ " for i, g in enumerate(groups):\n",
74
+ " subset = df.filter(pl.col(\"domains\").is_in(g))\n",
75
+ " metrics = get_part_metrics(subset, threshold=threshold)\n",
76
+ " metrics[\"group\"] = group_names[i]\n",
77
+ " all_metrics.append(metrics)\n",
78
+ " \n",
79
+ " return pd.DataFrame(all_metrics)"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "# Load the data from the output files\n",
89
+ "df1 = pl.read_csv('/Users/fionachow/Downloads/outputs/preds-image-classifier-1.csv')\n",
90
+ "df14 = pl.read_csv('/Users/fionachow/Downloads/outputs/preds-image-classifier-14.csv')\n",
91
+ "df142 = pl.read_csv('/Users/fionachow/Downloads/outputs/preds-image-classifier-142.csv')\n",
92
+ "df1423 = pl.read_csv('/Users/fionachow/Downloads/outputs/preds-image-classifier-1423.csv')\n",
93
+ "\n",
94
+ "metrics_df1 = get_all_metrics(df1, threshold=0.5)\n",
95
+ "metrics_df14 = get_all_metrics(df14, threshold=0.5)\n",
96
+ "metrics_df142 = get_all_metrics(df142, threshold=0.5)\n",
97
+ "metrics_df1423 = get_all_metrics(df1423, threshold=0.5)"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": null,
103
+ "metadata": {},
104
+ "outputs": [],
105
+ "source": [
106
+ "metrics_df1.info()"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": null,
112
+ "metadata": {},
113
+ "outputs": [],
114
+ "source": [
115
+ "sns.set()\n",
116
+ "\n",
117
+ "models = ['StableDiffusion', 'Midjourney', 'Dalle2', 'Dalle3']\n",
118
+ "metrics = ['accuracy', 'f1', 'pf1', 'roc_auc']\n",
119
+ "\n",
120
+ "file_map = {\n",
121
+ " ('StableDiffusion',): metrics_df1,\n",
122
+ " ('StableDiffusion', 'Midjourney'): metrics_df14,\n",
123
+ " ('StableDiffusion', 'Midjourney', 'Dalle2'): metrics_df142,\n",
124
+ " ('StableDiffusion', 'Midjourney', 'Dalle2', 'Dalle3'): metrics_df1423,\n",
125
+ "}\n",
126
+ "\n",
127
+ "def create_heatmap_data(metric):\n",
128
+ " data = pd.DataFrame(index=models[::-1], columns=models)\n",
129
+ " for i, model_x in enumerate(models):\n",
130
+ " for j, model_y in enumerate(models[::-1]):\n",
131
+ " \n",
132
+ " if i == 0:\n",
133
+ " relevant_df = metrics_df1\n",
134
+ " elif i == 1:\n",
135
+ " relevant_df = metrics_df14\n",
136
+ " elif i == 2:\n",
137
+ " relevant_df = metrics_df142\n",
138
+ " else:\n",
139
+ " relevant_df = metrics_df1423\n",
140
+ "\n",
141
+ " # Debugging: print the DataFrame being used and the model_y\n",
142
+ " #print(f\"Using DataFrame for {models[:i+1]}, model_y: {model_y}\")\n",
143
+ "\n",
144
+ " # Extract the metric value\n",
145
+ " if model_y in relevant_df['group'].values:\n",
146
+ " metric_value = relevant_df[relevant_df['group'] == model_y][metric].values[0]\n",
147
+ " # Debugging: print the extracted metric value\n",
148
+ " #print(f\"Metric value for {model_y}: {metric_value}\")\n",
149
+ " else:\n",
150
+ " metric_value = float('nan') # Handle non-existent cases\n",
151
+ " # Debugging: print a message for non-existent cases\n",
152
+ " #print(f\"No data for combination: {model_x}, {model_y}\")\n",
153
+ "\n",
154
+ " data.at[model_y, model_x] = metric_value\n",
155
+ " \n",
156
+ " for col in data.columns:\n",
157
+ " data[col] = pd.to_numeric(data[col], errors='coerce')\n",
158
+ "\n",
159
+ " # Debugging: print the final DataFrame\n",
160
+ " # print(f\"Final Data for metric {metric}:\")\n",
161
+ " # print(data)\n",
162
+ " # print(data.dtypes)\n",
163
+ " return data\n",
164
+ "\n",
165
+ "for metric in metrics:\n",
166
+ " plt.figure(figsize=(10, 8))\n",
167
+ " sns.heatmap(create_heatmap_data(metric), annot=True, cmap='coolwarm', fmt='.3f')\n",
168
+ " plt.title(f\"Heatmap for {metric}\")\n",
169
+ " plt.xlabel(\"Trained On (x-axis)\")\n",
170
+ " plt.ylabel(\"Tested On (y-axis)\")\n",
171
+ " plt.show()"
172
+ ]
173
+ }
174
+ ],
175
+ "metadata": {
176
+ "kernelspec": {
177
+ "display_name": "bloom",
178
+ "language": "python",
179
+ "name": "python3"
180
+ },
181
+ "language_info": {
182
+ "codemirror_mode": {
183
+ "name": "ipython",
184
+ "version": 3
185
+ },
186
+ "file_extension": ".py",
187
+ "mimetype": "text/x-python",
188
+ "name": "python",
189
+ "nbconvert_exporter": "python",
190
+ "pygments_lexer": "ipython3",
191
+ "version": "3.9.16"
192
+ }
193
+ },
194
+ "nbformat": 4,
195
+ "nbformat_minor": 2
196
+ }
src/images/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI-generated image detection
2
+ **(Work In Progress)**
3
+
4
+ - [ ] Refactor code
5
+ - [ ] Review dependencies
6
+ - [ ] Containerize (Docker)
7
+ - [ ] Update documentation
8
+
9
+ ## AI-Generated Image detection
10
+
11
+ This part handles the detection of AI-generated images.
12
+ The current code contains two classifiers to detect AI-generated images from two types of architectures:
13
+ - GANs
14
+
15
+ ## Model weights
16
+
17
+ ### 1. CNN Detection
18
+
19
+ Run the `download_weights_CNN.sh` script:
20
+
21
+ ```commandline
22
+ bash download_weights_CNN.sh
23
+ ```
24
+
25
+ Note: you need `wget` installed on your system (it is by default for most Linux systems).
26
+
27
+ ### 2. Diffusion
28
+
29
+ **TODO**
30
+
31
+
32
+ ## Run the models
33
+
34
+ Make sure you have the weights available before doing so.
35
+
36
+ **TODO: environments**
37
+
38
+ ### 1. CNN Detection
39
+
40
+ ```commandline
41
+ python CNN_model_classifier.py
42
+ ```
43
+ Available options:
44
+
45
+ - `-f / --file` (default=`'examples_realfakedir'`)
46
+ - `-m / --model_path` (default=`'weights/blur_jpg_prob0.5.pth'`)
47
+ - `-c / --crop` (default=`None`): Specify crop size (int) by default, do not crop.
48
+ - `--use_cpu`: use cpu (by default uses GPU) -> **TODO: remove (obsolete)**
49
+
50
+ Example usage:
51
+
52
+ ```commandline
53
+ python CNN_model_classifier.py -f examples/real.png -m weights/blur_jpg_prob0.5.pth
54
+ ```
55
+
56
+ ### 2. Diffusion detection
57
+
58
+ **TODO**
59
+
60
+ ## References
61
+
62
+ Based on:
63
+ - https://github.com/hoangthuc701/GenAI-image-detection
64
+ - https://github.com/ptmaimai106/DetectGenerateImageByRealImageOnly
src/images/Search_Image/Bing_search.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from dotenv import load_dotenv
4
+ import requests
5
+
6
+ # Load Bing Search API key
7
+ load_dotenv()
8
+ BING_API_KEY = os.getenv("BING_API_KEY")
9
+
10
+ def print_json(obj):
11
+ """Print the object as json"""
12
+ print(json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')))
13
+
14
+
15
+ def get_image_urls(search_results):
16
+ """
17
+ Extracts image URLs from Bing Visual Search response.
18
+ Ref: https://learn.microsoft.com/en-us/bing/search-apis/bing-visual-search/how-to/search-response
19
+
20
+ Args:
21
+ search_results: A dict containing the Bing VisualSearch response data.
22
+
23
+ Returns:
24
+ A tuple containing two lists:
25
+ - List of image URLs from "PagesIncluding" section.
26
+ - List of image URLs from "VisualSearch" section (backup).
27
+ """
28
+
29
+ pages_including_urls = []
30
+ visual_search_urls = []
31
+
32
+ if "tags" not in search_results:
33
+ return pages_including_urls, visual_search_urls
34
+
35
+ # Check for required keys directly
36
+ if not any(action.get("actions") for action in search_results["tags"]):
37
+ return pages_including_urls, visual_search_urls
38
+
39
+
40
+ for action in search_results["tags"]:
41
+ for result in action.get("actions", []):
42
+ # actions = PagesIncluding, main results
43
+ if result["name"] == "PagesIncluding":
44
+ pages_including_urls.extend(item["contentUrl"] for item in result["data"]["value"])
45
+ # actions = VisualSearch, back up results
46
+ elif result["name"] == "VisualSearch":
47
+ visual_search_urls.extend(item["contentUrl"] for item in result["data"]["value"])
48
+
49
+ return pages_including_urls, visual_search_urls
50
+
51
+ def reverse_image_search(image_path, subscription_key=BING_API_KEY):
52
+ """Performs a reverse image search using the Bing Visual Search API.
53
+
54
+ Args:
55
+ image_path: The path to the image file to search for.
56
+
57
+ Returns:
58
+ A list of image URLs found that are similar to the image in the
59
+ specified path.
60
+
61
+ Raises:
62
+ requests.exceptions.RequestException: If the API request fails.
63
+ """
64
+ base_uri = "https://api.bing.microsoft.com/v7.0/images/visualsearch"
65
+ headers = {"Ocp-Apim-Subscription-Key": subscription_key}
66
+
67
+ try:
68
+ files = {"image": ("image", open(image_path, "rb"))}
69
+ response = requests.post(base_uri, headers=headers, files=files)
70
+ response.raise_for_status()
71
+ search_results = response.json()
72
+
73
+ return search_results
74
+
75
+ except requests.exceptions.RequestException as e:
76
+ raise requests.exceptions.RequestException(f"API request failed: {e}")
77
+ except OSError as e:
78
+ raise OSError(f"Error opening image file: {e}")
79
+
80
+ if __name__ == "__main__":
81
+ # Example usage:
82
+ image_path = "data/test_data/human_news.jpg"
83
+ try:
84
+ search_results = reverse_image_search(image_path)
85
+ image_urls, backup_image_urls = get_image_urls(search_results)
86
+
87
+ # Print the results
88
+ print("Image URLs from PagesIncluding:")
89
+ print(image_urls)
90
+ print("\nImage URLs from VisualSearch (backup):")
91
+ print(backup_image_urls)
92
+ except Exception as e:
93
+ print(f"An error occurred: {e}")
src/images/Search_Image/image_difference.py ADDED
File without changes
src/images/Search_Image/image_model_share.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.metrics import roc_auc_score
2
+ from torchmetrics import Accuracy, Recall
3
+ import pytorch_lightning as pl
4
+ import timm
5
+ import torch
6
+ from pytorch_lightning.callbacks import Model, EarlyStopping
7
+ import logging
8
+ from PIL import Image
9
+ import torchvision.transforms as transforms
10
+ from torchvision.transforms import v2
11
+
12
+ logging.basicConfig(filename='training.log',filemode='w',level=logging.INFO, force=True)
13
+ CHECKPOINT = "models/image_classifier/image-classifier-step=8008-val_loss=0.11.ckpt"
14
+
15
+
16
+
17
+ class ImageClassifier(pl.LightningModule):
18
+ def __init__(self, lmd=0):
19
+ super().__init__()
20
+ self.model = timm.create_model('resnet50', pretrained=True, num_classes=1)
21
+ self.accuracy = Accuracy(task='binary', threshold=0.5)
22
+ self.recall = Recall(task='binary', threshold=0.5)
23
+ self.validation_outputs = []
24
+ self.lmd = lmd
25
+
26
+ def forward(self, x):
27
+ return self.model(x)
28
+
29
+ def training_step(self, batch):
30
+ images, labels, _ = batch
31
+ outputs = self.forward(images).squeeze()
32
+
33
+ print(f"Shape of outputs (training): {outputs.shape}")
34
+ print(f"Shape of labels (training): {labels.shape}")
35
+
36
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
37
+ logging.info(f"Training Step - ERM loss: {loss.item()}")
38
+ loss += self.lmd * (outputs ** 2).mean() # SD loss penalty
39
+ logging.info(f"Training Step - SD loss: {loss.item()}")
40
+ return loss
41
+
42
+ def validation_step(self, batch):
43
+ images, labels, _ = batch
44
+ outputs = self.forward(images).squeeze()
45
+
46
+ if outputs.shape == torch.Size([]):
47
+ return
48
+
49
+ print(f"Shape of outputs (validation): {outputs.shape}")
50
+ print(f"Shape of labels (validation): {labels.shape}")
51
+
52
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
53
+ preds = torch.sigmoid(outputs)
54
+ self.log('val_loss', loss, prog_bar=True, sync_dist=True)
55
+ self.log('val_acc', self.accuracy(preds, labels.int()), prog_bar=True, sync_dist=True)
56
+ self.log('val_recall', self.recall(preds, labels.int()), prog_bar=True, sync_dist=True)
57
+ output = {"val_loss": loss, "preds": preds, "labels": labels}
58
+ self.validation_outputs.append(output)
59
+ logging.info(f"Validation Step - Batch loss: {loss.item()}")
60
+ return output
61
+
62
+ def predict_step(self, batch):
63
+ images, label, domain = batch
64
+ outputs = self.forward(images).squeeze()
65
+ preds = torch.sigmoid(outputs)
66
+ return preds, label, domain
67
+
68
+ def on_validation_epoch_end(self):
69
+ if not self.validation_outputs:
70
+ logging.warning("No outputs in validation step to process")
71
+ return
72
+ preds = torch.cat([x['preds'] for x in self.validation_outputs])
73
+ labels = torch.cat([x['labels'] for x in self.validation_outputs])
74
+ if labels.unique().size(0) == 1:
75
+ logging.warning("Only one class in validation step")
76
+ return
77
+ auc_score = roc_auc_score(labels.cpu(), preds.cpu())
78
+ self.log('val_auc', auc_score, prog_bar=True, sync_dist=True)
79
+ logging.info(f"Validation Epoch End - AUC score: {auc_score}")
80
+ self.validation_outputs = []
81
+
82
+ def configure_optimizers(self):
83
+ optimizer = torch.optim.Adam(self.model.parameters(), lr=0.0005)
84
+ return optimizer
85
+
86
+
87
+
88
+ def load_image(image_path, transform=None):
89
+ image = Image.open(image_path).convert('RGB')
90
+
91
+ if transform:
92
+ image = transform(image)
93
+
94
+ return image
95
+
96
+
97
+ def predict_single_image(image_path, model, transform=None):
98
+ image = load_image(image_path, transform)
99
+
100
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
101
+
102
+ model.to(device)
103
+
104
+ image = image.to(device)
105
+
106
+ model.eval()
107
+
108
+ with torch.no_grad():
109
+ image = image.unsqueeze(0)
110
+ output = model(image).squeeze()
111
+ print(output)
112
+ prediction = torch.sigmoid(output).item()
113
+
114
+ return prediction
115
+
116
+
117
+ def image_generation_detection(image_path):
118
+ model = ImageClassifier.load_from_checkpoint(CHECKPOINT)
119
+
120
+ transform = v2.Compose([
121
+ transforms.ToTensor(),
122
+ v2.CenterCrop((256, 256)),
123
+ ])
124
+
125
+ prediction = predict_single_image(image_path, model, transform)
126
+ print("prediction",prediction)
127
+
128
+ result = ""
129
+ if prediction <= 0.2:
130
+ result += "Most likely human"
131
+ image_prediction_label = "HUMAN"
132
+ else:
133
+ result += "Most likely machine"
134
+ image_prediction_label = "MACHINE"
135
+ image_confidence = min(1, 0.5 + abs(prediction - 0.2))
136
+ result += f" with confidence = {round(image_confidence * 100, 2)}%"
137
+ image_confidence = round(image_confidence * 100, 2)
138
+ return image_prediction_label, image_confidence
139
+
140
+
141
+ if __name__ == "__main__":
142
+ pass
src/images/Search_Image/search.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google_img_source_search import ReverseImageSearcher
2
+ import requests
3
+ from io import BytesIO
4
+ from PIL import Image
5
+ import imagehash
6
+ from google_img_source_search import ReverseImageSearcher
7
+
8
+ def get_image_from_url(url):
9
+ response = requests.get(url)
10
+ return Image.open(BytesIO(response.content))
11
+
12
+ def standardize_image(image):
13
+ # Convert to RGB if needed
14
+ if image.mode in ('RGBA', 'LA'):
15
+ background = Image.new('RGB', image.size, (255, 255, 255))
16
+ background.paste(image, mask=image.split()[-1])
17
+ image = background
18
+ elif image.mode != 'RGB':
19
+ image = image.convert('RGB')
20
+
21
+ # Resize to standard size (e.g. 256x256)
22
+ standard_size = (256, 256)
23
+ image = image.resize(standard_size)
24
+
25
+ return image
26
+
27
+ def compare_images(image1, image2):
28
+ # Standardize both images first
29
+ img1_std = standardize_image(image1)
30
+ img2_std = standardize_image(image2)
31
+
32
+ hash1 = imagehash.average_hash(img1_std)
33
+ hash2 = imagehash.average_hash(img2_std)
34
+ return hash1 - hash2 # Returns the Hamming distance between the hashes
35
+
36
+ if __name__ == '__main__':
37
+ image_url = 'https://i.pinimg.com/originals/c4/50/35/c450352ac6ea8645ead206721673e8fb.png'
38
+
39
+ # Get the image from URL
40
+ url_image = get_image_from_url(image_url)
41
+
42
+ # Search image
43
+ rev_img_searcher = ReverseImageSearcher()
44
+ res = rev_img_searcher.search(image_url)
45
+
46
+ for search_item in res:
47
+ print(f'Title: {search_item.page_title}')
48
+ # print(f'Site: {search_item.page_url}')
49
+ print(f'Img: {search_item.image_url}\n')
50
+
51
+ # Compare each search result image with the input image
52
+ result_image = get_image_from_url(search_item.image_url)
53
+ result_difference = compare_images(result_image, url_image)
54
+ print(f"Difference with search result: {result_difference}")
55
+ if result_difference == 0:
56
+ break
src/images/Search_Image/search_2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import logging
3
+ import requests
4
+ from bs4 import BeautifulSoup
5
+ from typing import Dict, Optional
6
+ from urllib.parse import quote, urlparse
7
+
8
+ logging.basicConfig(
9
+ filename='error.log',
10
+ level=logging.INFO,
11
+ format='%(asctime)s | [%(levelname)s]: %(message)s',
12
+ datefmt='%m-%d-%Y / %I:%M:%S %p'
13
+ )
14
+
15
+ class SearchResults:
16
+ def __init__(self, results):
17
+ self.results = results
18
+
19
+ def __str__(self):
20
+ output = ""
21
+ for result in self.results:
22
+ output += "---\n"
23
+ output += f"Title: {result.get('title', 'Title not found')}\n"
24
+ output += f"Link: {result.get('link', 'Link not found')}\n"
25
+ output += "---\n"
26
+ return output
27
+
28
+ class GoogleReverseImageSearch:
29
+ def __init__(self):
30
+ self.base_url = "https://www.google.com/searchbyimage"
31
+ self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
32
+ self.retry_count = 3
33
+ self.retry_delay = 1
34
+
35
+ def response(self, query: str, image_url: str, max_results: int = 10, delay: int = 1) -> SearchResults:
36
+ self._validate_input(query, image_url)
37
+
38
+ encoded_query = quote(query)
39
+ encoded_image_url = quote(image_url)
40
+
41
+ url = f"{self.base_url}?q={encoded_query}&image_url={encoded_image_url}&sbisrc=cr_1_5_2"
42
+
43
+ all_results = []
44
+ start_index = 0
45
+
46
+ while len(all_results) < max_results:
47
+ if start_index != 0:
48
+ time.sleep(delay)
49
+
50
+ paginated_url = f"{url}&start={start_index}"
51
+
52
+ response = self._make_request(paginated_url)
53
+ if response is None:
54
+ break
55
+
56
+ search_results, valid_content = self._parse_search_results(response.text)
57
+ if not valid_content:
58
+ logging.warning("Unexpected HTML structure encountered.")
59
+ break
60
+
61
+ for result in search_results:
62
+ if len(all_results) >= max_results:
63
+ break
64
+ data = self._extract_result_data(result)
65
+ if data and data not in all_results:
66
+ all_results.append(data)
67
+
68
+ start_index += (len(all_results)-start_index)
69
+
70
+ if len(all_results) == 0:
71
+ logging.warning(f"No results were found for the given query: [{query}], and/or image URL: [{image_url}].")
72
+ return "No results found. Please try again with a different query and/or image URL."
73
+ else:
74
+ return SearchResults(all_results[:max_results])
75
+
76
+ def _validate_input(self, query: str, image_url: str):
77
+ if not query:
78
+ raise ValueError("Query not found. Please enter a query and try again.")
79
+ if not image_url:
80
+ raise ValueError("Image URL not found. Please enter an image URL and try again.")
81
+ if not self._validate_image_url(image_url):
82
+ raise ValueError("Invalid image URL. Please enter a valid image URL and try again.")
83
+
84
+ def _validate_image_url(self, url: str) -> bool:
85
+ parsed_url = urlparse(url)
86
+ path = parsed_url.path.lower()
87
+ valid_extensions = (".jpg", ".jpeg", ".png", ".webp")
88
+ return any(path.endswith(ext) for ext in valid_extensions)
89
+
90
+ def _make_request(self, url: str):
91
+ attempts = 0
92
+ while attempts < self.retry_count:
93
+ try:
94
+ response = requests.get(url, headers=self.headers)
95
+ if response.headers.get('Content-Type', '').startswith('text/html'):
96
+ response.raise_for_status()
97
+ return response
98
+ else:
99
+ logging.warning("Non-HTML content received.")
100
+ return None
101
+ except requests.exceptions.HTTPError as http_err:
102
+ logging.error(f"HTTP error occurred: {http_err}")
103
+ attempts += 1
104
+ time.sleep(self.retry_delay)
105
+ except Exception as err:
106
+ logging.error(f"An error occurred: {err}")
107
+ return None
108
+ return None
109
+
110
+ def _parse_search_results(self, html_content: str) -> (Optional[list], bool):
111
+ try:
112
+ soup = BeautifulSoup(html_content, "html.parser")
113
+ return soup.find_all('div', class_='g'), True
114
+ except Exception as e:
115
+ logging.error(f"Error parsing HTML content: {e}")
116
+ return None, False
117
+
118
+ def _extract_result_data(self, result) -> Dict:
119
+ link = result.find('a', href=True)['href'] if result.find('a', href=True) else None
120
+ title = result.find('h3').get_text(strip=True) if result.find('h3') else None
121
+ return {"link": link, "title": title} if link and title else {}
122
+
123
+
124
+ if __name__ == "__main__":
125
+ # request = GoogleReverseImageSearch()
126
+
127
+ # response = request.response(
128
+ # query="Example Query",
129
+ # image_url="https://ichef.bbci.co.uk/images/ic/1024xn/p0khzhhl.jpg.webp",
130
+ # max_results=5
131
+ # )
132
+
133
+ # print(response)
134
+
135
+ # Path to local image
136
+ image_path = "data/test_data/towel.jpg"
137
+ image_path = "C:\\TTProjects\\prj-nict-ai-content-detection\\data\\test_data\\towel.jpg"
138
+
139
+ import json
140
+ file_path = image_path
141
+ search_url = 'https://yandex.ru/images/search'
142
+ files = {'upfile': ('blob', open(file_path, 'rb'), 'image/jpeg')}
143
+ params = {'rpt': 'imageview', 'format': 'json', 'request': '{"blocks":[{"block":"b-page_type_search-by-image__link"}]}'}
144
+ response = requests.post(search_url, params=params, files=files)
145
+ query_string = json.loads(response.content)['blocks'][0]['params']['url']
146
+ img_search_url = search_url + '?' + query_string
147
+ print(img_search_url)
148
+
149
+ response = requests.get(img_search_url)
150
+ print(response.text)
src/images/Search_Image/search_yandex.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import logging
3
+ import requests
4
+ from bs4 import BeautifulSoup
5
+ from typing import Dict, Optional
6
+ from urllib.parse import quote, urlparse
7
+
8
+ logging.basicConfig(
9
+ filename='error.log',
10
+ level=logging.INFO,
11
+ format='%(asctime)s | [%(levelname)s]: %(message)s',
12
+ datefmt='%m-%d-%Y / %I:%M:%S %p'
13
+ )
14
+
15
+ class SearchResults:
16
+ def __init__(self, results):
17
+ self.results = results
18
+
19
+ def __str__(self):
20
+ output = ""
21
+ for result in self.results:
22
+ output += "---\n"
23
+ output += f"Title: {result.get('title', 'Title not found')}\n"
24
+ output += f"Link: {result.get('link', 'Link not found')}\n"
25
+ output += "---\n"
26
+ return output
27
+
28
+ class ReverseImageSearch:
29
+ def __init__(self):
30
+ self.base_url = "https://yandex.ru/images/search"
31
+ self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"}
32
+ self.retry_count = 3
33
+ self.retry_delay = 1
34
+
35
+ def response(self, query: str, image_url: str, max_results: int = 10, delay: int = 1) -> SearchResults:
36
+ self._validate_input(query, image_url)
37
+
38
+ encoded_query = quote(query)
39
+ encoded_image_url = quote(image_url)
40
+
41
+ url = f"{self.base_url}?q={encoded_query}&image_url={encoded_image_url}&sbisrc=cr_1_5_2"
42
+
43
+ all_results = []
44
+ start_index = 0
45
+
46
+ while len(all_results) < max_results:
47
+ if start_index != 0:
48
+ time.sleep(delay)
49
+
50
+ paginated_url = f"{url}&start={start_index}"
51
+
52
+ response = self._make_request(paginated_url)
53
+ if response is None:
54
+ break
55
+
56
+ search_results, valid_content = self._parse_search_results(response.text)
57
+ if not valid_content:
58
+ logging.warning("Unexpected HTML structure encountered.")
59
+ break
60
+
61
+ for result in search_results:
62
+ if len(all_results) >= max_results:
63
+ break
64
+ data = self._extract_result_data(result)
65
+ if data and data not in all_results:
66
+ all_results.append(data)
67
+
68
+ start_index += (len(all_results)-start_index)
69
+
70
+ if len(all_results) == 0:
71
+ logging.warning(f"No results were found for the given query: [{query}], and/or image URL: [{image_url}].")
72
+ return "No results found. Please try again with a different query and/or image URL."
73
+ else:
74
+ return SearchResults(all_results[:max_results])
75
+
76
+ def _validate_input(self, query: str, image_url: str):
77
+ if not query:
78
+ raise ValueError("Query not found. Please enter a query and try again.")
79
+ if not image_url:
80
+ raise ValueError("Image URL not found. Please enter an image URL and try again.")
81
+ if not self._validate_image_url(image_url):
82
+ raise ValueError("Invalid image URL. Please enter a valid image URL and try again.")
83
+
84
+ def _validate_image_url(self, url: str) -> bool:
85
+ parsed_url = urlparse(url)
86
+ path = parsed_url.path.lower()
87
+ valid_extensions = (".jpg", ".jpeg", ".png", ".webp")
88
+ return any(path.endswith(ext) for ext in valid_extensions)
89
+
90
+ def _make_request(self, url: str):
91
+ attempts = 0
92
+ while attempts < self.retry_count:
93
+ try:
94
+ response = requests.get(url, headers=self.headers)
95
+ if response.headers.get('Content-Type', '').startswith('text/html'):
96
+ response.raise_for_status()
97
+ return response
98
+ else:
99
+ logging.warning("Non-HTML content received.")
100
+ return None
101
+ except requests.exceptions.HTTPError as http_err:
102
+ logging.error(f"HTTP error occurred: {http_err}")
103
+ attempts += 1
104
+ time.sleep(self.retry_delay)
105
+ except Exception as err:
106
+ logging.error(f"An error occurred: {err}")
107
+ return None
108
+ return None
109
+
110
+ def _parse_search_results(self, html_content: str) -> (Optional[list], bool):
111
+ try:
112
+ soup = BeautifulSoup(html_content, "html.parser")
113
+ return soup.find_all('div', class_='g'), True
114
+ except Exception as e:
115
+ logging.error(f"Error parsing HTML content: {e}")
116
+ return None, False
117
+
118
+ def _extract_result_data(self, result) -> Dict:
119
+ link = result.find('a', href=True)['href'] if result.find('a', href=True) else None
120
+ title = result.find('h3').get_text(strip=True) if result.find('h3') else None
121
+ return {"link": link, "title": title} if link and title else {}
122
+
123
+ def yandex_reverse_image_search(image_url):
124
+ # Simulate a user agent to avoid being blocked
125
+ headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
126
+
127
+ try:
128
+ response = requests.get(image_url, headers=headers)
129
+ response.raise_for_status() # Raise an exception for bad status codes
130
+
131
+ # Parse the HTML content
132
+ soup = BeautifulSoup(response.content, 'html.parser')
133
+
134
+ # Extract image URLs (example - adapt based on Yandex's HTML structure)
135
+ image_urls = [img['src'] for img in soup.find_all('img')]
136
+
137
+ # Extract related searches (example - adapt based on Yandex's HTML structure)
138
+ related_searches = [text for text in soup.find_all(class_="related-searches")]
139
+
140
+ return image_urls, related_searches
141
+
142
+ except requests.exceptions.RequestException as e:
143
+ print(f"Error fetching image: {e}")
144
+ return [], []
145
+
146
+
147
+ if __name__ == "__main__":
148
+ # request = GoogleReverseImageSearch()
149
+
150
+ # response = request.response(
151
+ # query="Example Query",
152
+ # image_url="https://ichef.bbci.co.uk/images/ic/1024xn/p0khzhhl.jpg.webp",
153
+ # max_results=5
154
+ # )
155
+
156
+ # print(response)
157
+
158
+ # Path to local image
159
+ image_path = "data/test_data/towel.jpg"
160
+ image_path = "C:\\TTProjects\\prj-nict-ai-content-detection\\data\\test_data\\towel.jpg"
161
+
162
+ import json
163
+ file_path = image_path
164
+ search_url = 'https://yandex.ru/images/search'
165
+ files = {'upfile': ('blob', open(file_path, 'rb'), 'image/jpeg')}
166
+ params = {'rpt': 'imageview', 'format': 'json', 'request': '{"blocks":[{"block":"b-page_type_search-by-image__link"}]}'}
167
+ response = requests.post(search_url, params=params, files=files)
168
+ query_string = json.loads(response.content)['blocks'][0]['params']['url']
169
+ img_search_url = search_url + '?' + query_string
170
+ print(img_search_url)
171
+
172
+ image_urls, related_searches = yandex_reverse_image_search(img_search_url)
173
+
174
+ print("Image URLs:", image_urls)
175
+ print("Related Searches:", related_searches)
176
+
177
+
src/images/diffusion_data_loader.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import collections
3
+ import random
4
+ from typing import Iterator
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import torchdata.datapipes as dp
9
+ from imwatermark import WatermarkEncoder
10
+ from PIL import (
11
+ Image,
12
+ ImageFile,
13
+ )
14
+ from torch.utils.data import DataLoader
15
+ from torchdata.datapipes.iter import (
16
+ Concater,
17
+ FileLister,
18
+ FileOpener,
19
+ SampleMultiplexer,
20
+ )
21
+ from torchvision.transforms import v2
22
+ from tqdm import tqdm
23
+
24
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
25
+ Image.MAX_IMAGE_PIXELS = 1000000000
26
+
27
+ encoder = WatermarkEncoder()
28
+ encoder.set_watermark("bytes", b"test")
29
+
30
+ DOMAIN_LABELS = {
31
+ 0: "laion",
32
+ 1: "StableDiffusion",
33
+ 2: "dalle2",
34
+ 3: "dalle3",
35
+ 4: "midjourney",
36
+ }
37
+
38
+ N_SAMPLES = {
39
+ 0: (115346, 14418, 14419),
40
+ 1: (22060, 2757, 2758),
41
+ 4: (21096, 2637, 2637),
42
+ 2: (13582, 1697, 1699),
43
+ 3: (12027, 1503, 1504),
44
+ }
45
+
46
+
47
+ @dp.functional_datapipe("collect_from_workers")
48
+ class WorkerResultCollector(dp.iter.IterDataPipe):
49
+ def __init__(self, source: dp.iter.IterDataPipe):
50
+ self.source = source
51
+
52
+ def __iter__(self) -> Iterator:
53
+ yield from self.source
54
+
55
+ def is_replicable(self) -> bool:
56
+ """Method to force data back to main process"""
57
+ return False
58
+
59
+
60
+ def crop_bottom(image, cutoff=16):
61
+ return image[:, :-cutoff, :]
62
+
63
+
64
+ def random_gaussian_blur(image, p=0.01):
65
+ if random.random() < p:
66
+ return v2.functional.gaussian_blur(image, kernel_size=5)
67
+ return image
68
+
69
+
70
+ def random_invisible_watermark(image, p=0.2):
71
+ image_np = np.array(image)
72
+ image_np = np.transpose(image_np, (1, 2, 0))
73
+
74
+ if image_np.ndim == 2: # Grayscale image
75
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2BGR)
76
+ elif image_np.shape[2] == 4: # RGBA image
77
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2BGR)
78
+
79
+ if image_np.shape[0] < 256 or image_np.shape[1] < 256:
80
+ image_np = cv2.resize(
81
+ image_np,
82
+ (256, 256),
83
+ interpolation=cv2.INTER_AREA,
84
+ )
85
+
86
+ if random.random() < p:
87
+ return encoder.encode(image_np, method="dwtDct")
88
+
89
+ return image_np
90
+
91
+
92
+ def build_transform(split: str):
93
+ train_transform = v2.Compose(
94
+ [
95
+ v2.Lambda(crop_bottom),
96
+ v2.RandomCrop((256, 256), pad_if_needed=True),
97
+ v2.Lambda(random_gaussian_blur),
98
+ v2.RandomGrayscale(p=0.05),
99
+ v2.Lambda(random_invisible_watermark),
100
+ v2.ToImage(),
101
+ ],
102
+ )
103
+
104
+ eval_transform = v2.Compose(
105
+ [
106
+ v2.CenterCrop((256, 256)),
107
+ ],
108
+ )
109
+ transform = train_transform if split == "train" else eval_transform
110
+
111
+ return transform
112
+
113
+
114
+ def dp_to_tuple_train(input_dict):
115
+ transform = build_transform("train")
116
+ return (
117
+ transform(input_dict[".jpg"]),
118
+ input_dict[".label.cls"],
119
+ input_dict[".domain_label.cls"],
120
+ )
121
+
122
+
123
+ def dp_to_tuple_eval(input_dict):
124
+ transform = build_transform("eval")
125
+ return (
126
+ transform(input_dict[".jpg"]),
127
+ input_dict[".label.cls"],
128
+ input_dict[".domain_label.cls"],
129
+ )
130
+
131
+
132
+ def load_dataset(domains: list[int], split: str):
133
+ laion_lister = FileLister("./data/laion400m_data", f"{split}*.tar")
134
+ genai_lister = {
135
+ d: FileLister(
136
+ f"./data/genai-images/{DOMAIN_LABELS[d]}",
137
+ f"{split}*.tar",
138
+ )
139
+ for d in domains
140
+ if DOMAIN_LABELS[d] != "laion"
141
+ }
142
+ weight_genai = 1 / len(genai_lister)
143
+
144
+ def open_lister(lister):
145
+ opener = FileOpener(lister, mode="b")
146
+ return opener.load_from_tar().routed_decode().webdataset()
147
+
148
+ buffer_size1 = 100 if split == "train" else 10
149
+ buffer_size2 = 100 if split == "train" else 10
150
+
151
+ if split != "train":
152
+ all_lister = [laion_lister] + list(genai_lister.values())
153
+ dp = open_lister(Concater(*all_lister)).sharding_filter()
154
+ else:
155
+ laion_dp = (
156
+ open_lister(laion_lister.shuffle())
157
+ .cycle()
158
+ .sharding_filter()
159
+ .shuffle(buffer_size=buffer_size1)
160
+ )
161
+ genai_dp = {
162
+ open_lister(genai_lister[d].shuffle())
163
+ .cycle()
164
+ .sharding_filter()
165
+ .shuffle(
166
+ buffer_size=buffer_size1,
167
+ ): weight_genai
168
+ for d in domains
169
+ if DOMAIN_LABELS[d] != "laion"
170
+ }
171
+ dp = SampleMultiplexer({laion_dp: 1, **genai_dp}).shuffle(
172
+ buffer_size=buffer_size2,
173
+ )
174
+
175
+ if split == "train":
176
+ dp = dp.map(dp_to_tuple_train)
177
+ else:
178
+ dp = dp.map(dp_to_tuple_eval)
179
+
180
+ return dp
181
+
182
+
183
+ def load_dataloader(
184
+ domains: list[int],
185
+ split: str,
186
+ batch_size: int = 32,
187
+ num_workers: int = 4,
188
+ ):
189
+ dp = load_dataset(domains, split)
190
+ # if split == "train":
191
+ # dp = UnderSamplerIterDataPipe(dp, {0: 0.5, 1: 0.5}, seed=42)
192
+ dp = dp.batch(batch_size).collate()
193
+ dl = DataLoader(
194
+ dp,
195
+ batch_size=None,
196
+ num_workers=num_workers,
197
+ pin_memory=True,
198
+ )
199
+
200
+ return dl
201
+
202
+
203
+ if __name__ == "__main__":
204
+ parser = argparse.ArgumentParser()
205
+
206
+ args = parser.parse_args()
207
+
208
+ # testing code
209
+ dl = load_dataloader([0, 1], "train", num_workers=8)
210
+ y_dist = collections.Counter()
211
+ d_dist = collections.Counter()
212
+
213
+ for i, (img, y, d) in tqdm(enumerate(dl)):
214
+ if i % 100 == 0:
215
+ print(y, d)
216
+ if i == 400:
217
+ break
218
+ y_dist.update(y.numpy())
219
+ d_dist.update(d.numpy())
220
+
221
+ print("class label")
222
+ for label in sorted(y_dist):
223
+ frequency = y_dist[label] / sum(y_dist.values())
224
+ print(f"• {label}: {frequency:.2%} ({y_dist[label]})")
225
+
226
+ print("domain label")
227
+ for label in sorted(d_dist):
228
+ frequency = d_dist[label] / sum(d_dist.values())
229
+ print(f"• {label}: {frequency:.2%} ({d_dist[label]})")
src/images/diffusion_model_classifier.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+
5
+ import pandas as pd
6
+ import pytorch_lightning as pl
7
+ import timm
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torchvision.transforms as transforms
11
+ from PIL import Image
12
+ from pytorch_lightning.callbacks import (
13
+ EarlyStopping,
14
+ ModelCheckpoint,
15
+ )
16
+ from sklearn.metrics import roc_auc_score
17
+ from torchmetrics import (
18
+ Accuracy,
19
+ Recall,
20
+ )
21
+
22
+ from .diffusion_data_loader import load_dataloader
23
+
24
+
25
+ class ImageClassifier(pl.LightningModule):
26
+ def __init__(self, lmd=0):
27
+ super().__init__()
28
+ self.model = timm.create_model(
29
+ "resnet50",
30
+ pretrained=True,
31
+ num_classes=1,
32
+ )
33
+ self.accuracy = Accuracy(task="binary", threshold=0.5)
34
+ self.recall = Recall(task="binary", threshold=0.5)
35
+ self.validation_outputs = []
36
+ self.lmd = lmd
37
+
38
+ def forward(self, x):
39
+ return self.model(x)
40
+
41
+ def training_step(self, batch):
42
+ images, labels, _ = batch
43
+ outputs = self.forward(images).squeeze()
44
+
45
+ print(f"Shape of outputs (training): {outputs.shape}")
46
+ print(f"Shape of labels (training): {labels.shape}")
47
+
48
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
49
+ logging.info(f"Training Step - ERM loss: {loss.item()}")
50
+ loss += self.lmd * (outputs**2).mean() # SD loss penalty
51
+ logging.info(f"Training Step - SD loss: {loss.item()}")
52
+ return loss
53
+
54
+ def validation_step(self, batch):
55
+ images, labels, _ = batch
56
+ outputs = self.forward(images).squeeze()
57
+
58
+ if outputs.shape == torch.Size([]):
59
+ return
60
+
61
+ print(f"Shape of outputs (validation): {outputs.shape}")
62
+ print(f"Shape of labels (validation): {labels.shape}")
63
+
64
+ loss = F.binary_cross_entropy_with_logits(outputs, labels.float())
65
+ preds = torch.sigmoid(outputs)
66
+ self.log("val_loss", loss, prog_bar=True, sync_dist=True)
67
+ self.log(
68
+ "val_acc",
69
+ self.accuracy(preds, labels.int()),
70
+ prog_bar=True,
71
+ sync_dist=True,
72
+ )
73
+ self.log(
74
+ "val_recall",
75
+ self.recall(preds, labels.int()),
76
+ prog_bar=True,
77
+ sync_dist=True,
78
+ )
79
+ output = {"val_loss": loss, "preds": preds, "labels": labels}
80
+ self.validation_outputs.append(output)
81
+ logging.info(f"Validation Step - Batch loss: {loss.item()}")
82
+ return output
83
+
84
+ def predict_step(self, batch):
85
+ images, label, domain = batch
86
+ outputs = self.forward(images).squeeze()
87
+ preds = torch.sigmoid(outputs)
88
+ return preds, label, domain
89
+
90
+ def on_validation_epoch_end(self):
91
+ if not self.validation_outputs:
92
+ logging.warning("No outputs in validation step to process")
93
+ return
94
+ preds = torch.cat([x["preds"] for x in self.validation_outputs])
95
+ labels = torch.cat([x["labels"] for x in self.validation_outputs])
96
+ if labels.unique().size(0) == 1:
97
+ logging.warning("Only one class in validation step")
98
+ return
99
+ auc_score = roc_auc_score(labels.cpu(), preds.cpu())
100
+ self.log("val_auc", auc_score, prog_bar=True, sync_dist=True)
101
+ logging.info(f"Validation Epoch End - AUC score: {auc_score}")
102
+ self.validation_outputs = []
103
+
104
+ def configure_optimizers(self):
105
+ optimizer = torch.optim.Adam(self.model.parameters(), lr=0.0005)
106
+ return optimizer
107
+
108
+
109
+ def load_image(image_path, transform=None):
110
+ image = Image.open(image_path).convert("RGB")
111
+
112
+ if transform:
113
+ image = transform(image)
114
+
115
+ return image
116
+
117
+
118
+ def predict_single_image(image, model):
119
+
120
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
121
+
122
+ model.to(device)
123
+
124
+ image = image.to(device)
125
+
126
+ model.eval()
127
+
128
+ with torch.no_grad():
129
+ image = image.unsqueeze(0)
130
+ output = model(image).squeeze()
131
+ prediction = torch.sigmoid(output).item()
132
+
133
+ return prediction
134
+
135
+
136
+ if __name__ == "__main__":
137
+ checkpoint_callback = ModelCheckpoint(
138
+ monitor="val_loss",
139
+ dirpath="./model_checkpoints/",
140
+ filename="image-classifier-{step}-{val_loss:.2f}",
141
+ save_top_k=3,
142
+ mode="min",
143
+ every_n_train_steps=1001,
144
+ enable_version_counter=True,
145
+ )
146
+
147
+ early_stop_callback = EarlyStopping(
148
+ monitor="val_loss",
149
+ patience=4,
150
+ mode="min",
151
+ )
152
+
153
+ parser = argparse.ArgumentParser()
154
+ parser.add_argument(
155
+ "--ckpt_path",
156
+ help="checkpoint to continue from",
157
+ required=False,
158
+ )
159
+ parser.add_argument(
160
+ "--predict",
161
+ help="predict on test set",
162
+ action="store_true",
163
+ )
164
+ parser.add_argument("--reset", help="reset training", action="store_true")
165
+ parser.add_argument(
166
+ "--predict_image",
167
+ help="predict the class of a single image",
168
+ action="store_true",
169
+ )
170
+ parser.add_argument(
171
+ "--image_path",
172
+ help="path to the image to predict",
173
+ type=str,
174
+ required=False,
175
+ )
176
+ parser.add_argument(
177
+ "--dir",
178
+ help="path to the images to predict",
179
+ type=str,
180
+ required=False,
181
+ )
182
+ parser.add_argument(
183
+ "--output_file",
184
+ help="path to output file",
185
+ type=str,
186
+ required=False,
187
+ )
188
+ args = parser.parse_args()
189
+
190
+ train_domains = [0, 1, 4]
191
+ val_domains = [0, 1, 4]
192
+ lmd_value = 0
193
+
194
+ if args.predict:
195
+ test_dl = load_dataloader(
196
+ [0, 1, 2, 3, 4],
197
+ "test",
198
+ batch_size=10,
199
+ num_workers=1,
200
+ )
201
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
202
+ trainer = pl.Trainer()
203
+ predictions = trainer.predict(model, dataloaders=test_dl)
204
+ preds, labels, domains = zip(*predictions)
205
+ preds = torch.cat(preds).cpu().numpy()
206
+ labels = torch.cat(labels).cpu().numpy()
207
+ domains = torch.cat(domains).cpu().numpy()
208
+ print(preds.shape, labels.shape, domains.shape)
209
+ df = pd.DataFrame(
210
+ {"preds": preds, "labels": labels, "domains": domains},
211
+ )
212
+ filename = "preds-" + args.ckpt_path.split("/")[-1]
213
+ df.to_csv(f"outputs/{filename}.csv", index=False)
214
+ elif args.predict_image:
215
+ image_path = args.image_path
216
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
217
+
218
+ # Define the transformations for the image
219
+ transform = transforms.Compose(
220
+ [
221
+ transforms.CenterCrop((256, 256)),
222
+ transforms.ToTensor(),
223
+ ],
224
+ )
225
+ image = load_image(image_path, transform)
226
+ prediction = predict_single_image(image, model)
227
+ print("prediction", prediction)
228
+
229
+ # Output the prediction
230
+ print(
231
+ f"Prediction for {image_path}: "
232
+ f"{'Human' if prediction <= 0.05 else 'Generated'}",
233
+ )
234
+ elif args.dir is not None:
235
+ predictions = []
236
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
237
+ transform = transforms.Compose(
238
+ [
239
+ transforms.CenterCrop((256, 256)),
240
+ transforms.ToTensor(),
241
+ ],
242
+ )
243
+ for root, dirs, files in os.walk(os.path.abspath(args.dir)):
244
+ for f_name in files:
245
+ f = os.path.join(root, f_name)
246
+ print(f"Predicting: {f}")
247
+ p = predict_single_image(f, model)
248
+ predictions.append([f, f.split("/")[-2], p, p > 0.5])
249
+ print(f"--predicted: {p}")
250
+
251
+ df = pd.DataFrame(
252
+ predictions,
253
+ columns=["path", "folder", "pred", "class"],
254
+ )
255
+ df.to_csv(args.output_file, index=False)
256
+ else:
257
+ logging.basicConfig(
258
+ filename="training.log",
259
+ filemode="w",
260
+ level=logging.INFO,
261
+ force=True,
262
+ )
263
+ train_dl = load_dataloader(
264
+ train_domains,
265
+ "train",
266
+ batch_size=128,
267
+ num_workers=4,
268
+ )
269
+ logging.info("Training dataloader loaded")
270
+ val_dl = load_dataloader(
271
+ val_domains,
272
+ "val",
273
+ batch_size=128,
274
+ num_workers=4,
275
+ )
276
+ logging.info("Validation dataloader loaded")
277
+
278
+ if args.reset:
279
+ model = ImageClassifier.load_from_checkpoint(args.ckpt_path)
280
+ else:
281
+ model = ImageClassifier(lmd=lmd_value)
282
+ trainer = pl.Trainer(
283
+ callbacks=[checkpoint_callback, early_stop_callback],
284
+ max_steps=20000,
285
+ val_check_interval=1000,
286
+ check_val_every_n_epoch=None,
287
+ )
288
+ trainer.fit(
289
+ model=model,
290
+ train_dataloaders=train_dl,
291
+ val_dataloaders=val_dl,
292
+ ckpt_path=args.ckpt_path if not args.reset else None,
293
+ )
src/images/diffusion_utils_sampling.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import random
3
+ from typing import Callable
4
+
5
+ from torchdata.datapipes.iter import IterDataPipe
6
+
7
+
8
+ def get_second_entry(sample):
9
+ return sample[1]
10
+
11
+
12
+ class UnderSamplerIterDataPipe(IterDataPipe):
13
+ """Dataset wrapper for under-sampling.
14
+
15
+ Copied from: https://github.com/MaxHalford/pytorch-resample/blob/master/pytorch_resample/under.py # noqa
16
+ Modified to work with multiple labels.
17
+
18
+ MIT License
19
+
20
+ Copyright (c) 2020 Max Halford
21
+
22
+ This method is based on rejection sampling.
23
+
24
+ Parameters:
25
+ dataset
26
+ desired_dist: The desired class distribution.
27
+ The keys are the classes whilst the
28
+ values are the desired class percentages.
29
+ The values are normalised so that sum up
30
+ to 1.
31
+ label_getter: A function that takes a sample and returns its label.
32
+ seed: Random seed for reproducibility.
33
+
34
+ Attributes:
35
+ actual_dist: The counts of the observed sample labels.
36
+ rng: A random number generator instance.
37
+
38
+ References:
39
+ - https://www.wikiwand.com/en/Rejection_sampling
40
+
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ dataset: IterDataPipe,
46
+ desired_dist: dict,
47
+ label_getter: Callable = get_second_entry,
48
+ seed: int = None,
49
+ ):
50
+
51
+ self.dataset = dataset
52
+ self.desired_dist = {
53
+ c: p / sum(desired_dist.values()) for c, p in desired_dist.items()
54
+ }
55
+ self.label_getter = label_getter
56
+ self.seed = seed
57
+
58
+ self.actual_dist = collections.Counter()
59
+ self.rng = random.Random(seed)
60
+ self._pivot = None
61
+
62
+ def __iter__(self):
63
+
64
+ for dp in self.dataset:
65
+ y = self.label_getter(dp)
66
+
67
+ self.actual_dist[y] += 1
68
+
69
+ # To ease notation
70
+ f = self.desired_dist
71
+ g = self.actual_dist
72
+
73
+ # Check if the pivot needs to be changed
74
+ if y != self._pivot:
75
+ self._pivot = max(g.keys(), key=lambda y: f[y] / g[y])
76
+ else:
77
+ yield dp
78
+ continue
79
+
80
+ # Determine the sampling ratio if the observed label
81
+ # is not the pivot
82
+ M = f[self._pivot] / g[self._pivot]
83
+ ratio = f[y] / (M * g[y])
84
+
85
+ if ratio < 1 and self.rng.random() < ratio:
86
+ yield dp
87
+
88
+ @classmethod
89
+ def expected_size(cls, n, desired_dist, actual_dist):
90
+ M = max(
91
+ desired_dist.get(k) / actual_dist.get(k)
92
+ for k in set(desired_dist) | set(actual_dist)
93
+ )
94
+ return int(n / M)
src/images/image_demo.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torchvision.transforms as transforms
3
+ from CNN_model_classifier import predict_cnn
4
+ from diffusion_model_classifier import (
5
+ ImageClassifier,
6
+ predict_single_image,
7
+ )
8
+
9
+ gr.set_static_paths(paths=["samples/"])
10
+ diffusion_model = (
11
+ "Diffusion/model_checkpoints/image-classifier-step=7007-val_loss=0.09.ckpt"
12
+ )
13
+ cnn_model = "CNN/model_checkpoints/blur_jpg_prob0.5.pth"
14
+
15
+
16
+ def get_prediction_diffusion(image):
17
+ model = ImageClassifier.load_from_checkpoint(diffusion_model)
18
+
19
+ prediction = predict_single_image(image, model)
20
+ print(prediction)
21
+ return (prediction >= 0.001, prediction)
22
+
23
+
24
+ def get_prediction_cnn(image):
25
+ prediction = predict_cnn(image, cnn_model)
26
+ return (prediction >= 0.5, prediction)
27
+
28
+
29
+ def predict(inp):
30
+ # Define the transformations for the image
31
+ transform = transforms.Compose(
32
+ [
33
+ transforms.Resize((224, 224)), # Image size expected by ResNet50
34
+ transforms.ToTensor(),
35
+ transforms.Normalize(
36
+ mean=[0.485, 0.456, 0.406],
37
+ std=[0.229, 0.224, 0.225],
38
+ ),
39
+ ],
40
+ )
41
+ image_tensor = transform(inp)
42
+ pred_diff, prob_diff = get_prediction_diffusion(image_tensor)
43
+ pred_cnn, prob_cnn = get_prediction_cnn(image_tensor)
44
+ verdict = (
45
+ "AI Generated" if (pred_diff or pred_cnn) else "No GenAI detected"
46
+ )
47
+ return (
48
+ f"<h1>{verdict}</h1>"
49
+ f"<ul>"
50
+ f"<li>Diffusion detection score: {prob_diff:.2} "
51
+ f"{'(MATCH)' if pred_diff else ''}</li>"
52
+ f"<li>CNN detection score: {prob_cnn:.1%} "
53
+ f"{'(MATCH)' if pred_cnn else ''}</li>"
54
+ f"</ul>"
55
+ )
56
+
57
+
58
+ demo = gr.Interface(
59
+ title="AI-generated image detection",
60
+ description="Demo by NICT & Tokyo Techies ",
61
+ fn=predict,
62
+ inputs=gr.Image(type="pil"),
63
+ outputs=gr.HTML(),
64
+ examples=[
65
+ ["samples/fake_dalle.jpg", "Generated (Dall-E)"],
66
+ ["samples/fake_midjourney.png", "Generated (MidJourney)"],
67
+ ["samples/fake_stable.jpg", "Generated (Stable Diffusion)"],
68
+ ["samples/fake_cnn.png", "Generated (GAN)"],
69
+ ["samples/real.png", "Organic"],
70
+ ],
71
+ )
72
+
73
+ demo.launch()
src/main.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from texts.models import TextDetector
2
+
3
+
4
+ def extract_text_and_images(path: str):
5
+ text_content = ""
6
+ image_paths = ""
7
+ return text_content, image_paths
8
+
9
+
10
+ def process_document(document_path) -> list:
11
+ """
12
+ Processes a given document, separating text and images,
13
+ and then analyzes them.
14
+
15
+ Args:
16
+ document_path: Path to the document.
17
+
18
+ Returns:
19
+ A list containing the AI content percentage for text and images.
20
+ """
21
+
22
+ # Extract text and images from the document
23
+ text_content, image_paths = extract_text_and_images(document_path)
24
+
25
+ # Analyze text content
26
+ text_detector = TextDetector()
27
+ text_ai_content_percentage = text_detector.analyze_text(text_content)
28
+
29
+ # Analyze image content
30
+ image_ai_content_percentages = []
31
+ for image_path in image_paths:
32
+ # TODO: add image_detector class
33
+ # image_ai_content = image_detector.analyze_image(image_path)
34
+ image_ai_content = 100
35
+ image_ai_content_percentages.append(image_ai_content)
36
+
37
+ return [text_ai_content_percentage, image_ai_content_percentages]
38
+
39
+
40
+ def main():
41
+ document_path = "../data.pdf" # Replace with your document path
42
+ text_ai_content_percentage, image_ai_content_percentages = (
43
+ process_document(document_path)
44
+ )
45
+
46
+ print("Text AI Content Percentage:", text_ai_content_percentage)
47
+ print("Combined AI Content Percentage:", image_ai_content_percentages)
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
src/texts/MAGE/.gradio/flagged/dataset1.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ input text,AI-text detection,timestamp
2
+ Does Chicago have any stores and does Joe live here?,"[{""token"": ""Does Chicago have any stores and does Joe live here?"", ""class_or_confidence"": ""human-written""}]",2024-12-09 13:40:10.255451
src/texts/MAGE/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
src/texts/MAGE/README.md ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <p align="center">
3
+ <img src="./figures/intro.png" width="75%" height="75%" />
4
+ </p>
5
+ </div>
6
+
7
+ <div align="center">
8
+ <h1><img src="./figures/title.png" width="30px" height="30px" style="display:inline;margin-right:10px;">MAGE: Machine-generated Text Detection in the Wild</h1>
9
+ </div>
10
+
11
+ <div align="center">
12
+ <img src="https://img.shields.io/badge/Version-1.0.0-blue.svg" alt="Version">
13
+ <img src="https://img.shields.io/badge/License-CC%20BY%204.0-green.svg" alt="License">
14
+ <img src="https://img.shields.io/github/stars/yafuly/DeepfakeTextDetect?color=yellow" alt="Stars">
15
+ <img src="https://img.shields.io/github/issues/yafuly/DeepfakeTextDetect?color=red" alt="Issues">
16
+
17
+ <!-- **Authors:** -->
18
+ <br>
19
+
20
+ _**Yafu Li<sup>†</sup><sup>‡</sup>, Qintong Li<sup>§</sup>, Leyang Cui<sup>¶</sup>, Wei Bi<sup>¶</sup>,Zhilin Wang<sup>$</sup><br>**_
21
+
22
+ _**Longyue Wang<sup>¶</sup>, Linyi Yang<sup>‡</sup>, Shuming Shi<sup>¶</sup>, Yue Zhang<sup>‡</sup><br>**_
23
+
24
+ <!-- **Affiliations:** -->
25
+
26
+ _<sup>†</sup> Zhejiang University,
27
+ <sup>‡</sup> Westlake University,
28
+ <sup>§</sup> The University of Hong Kong,
29
+ <sup>$</sup> Jilin University,
30
+ <sup>¶</sup> Tencent AI Lab_
31
+
32
+ Presenting a comprehensive benchmark dataset designed to assess the proficiency of AI-generation detectors amidst real-world scenarios.
33
+ Welcome to try detection via our **[online demo](https://detect.westlake.edu.cn)**!
34
+
35
+ </div>
36
+
37
+ ## 📌 Table of Contents
38
+
39
+ - [Introduction](#-introduction)
40
+ - [Activities](#-activities)
41
+ - [Dataset](#-dataset)
42
+ - [Try Detection](#computer--try-detection)
43
+ - [Data Samples](#-data-samples)
44
+ - [Citation](#-citation)
45
+ <!-- - [Contributing](#-contributing) -->
46
+
47
+ ## 🚀 Introduction
48
+
49
+ Recent advances in large language models have enabled them to reach a level of text generation comparable to that of humans.
50
+ These models show powerful capabilities across a wide range of content, including news article writing, story generation, and scientific writing.
51
+ Such capability further narrows the gap between human-authored and machine-generated texts, highlighting the importance of machine-generated text detection to avoid potential risks such as fake news propagation and plagiarism.
52
+ In practical scenarios, the detector faces texts from various domains or LLMs without knowing their sources.
53
+
54
+ To this end, we build **a comprehensive testbed for deepfake text detection**, by gathering texts from various human writings and deepfake texts generated by different LLMs.
55
+ This repository contains the data to testify deepfake detection methods described in our paper, [MAGE: Machine-generated Text Detection in the Wild](https://aclanthology.org/2024.acl-long.3/).
56
+ Welcome to test your detection methods on our testbed!
57
+
58
+ ## 📅 Activities
59
+
60
+ - 🎉 **May 16, 2024**: Our paper was accepted by ACL 2024!
61
+ - 🎉 **June 19, 2023**: Update two 'wilder' testbeds! We go one step wilder by constructing an additional testset with texts from unseen domains generated by an unseen model, to testify the detection ability in more practical scenarios.
62
+ We consider four new datasets: CNN/DailyMail, DialogSum, PubMedQA and IMDb to test the detection of deepfake news, deepfake dialogues, deepfake scientific answers and deepfake movie reviews.
63
+ We sample 200 instances from each dataset and use a newly developed LLM, i.e., GPT-4, with specially designed prompts to create deepfake texts, establishing an "Unseen Domains & Unseen Model" scenario.
64
+ Previous work demonstrates that detection methods are vulnerable to being deceived by target texts.
65
+ Therefore, we also paraphrase each sentence individually for both human-written and machine-generated texts, forming an even more challenging testbed.
66
+ We adopt gpt-3.5-trubo as the zero-shot paraphraser and consider all paraphrased texts as machine-generated.
67
+ - May 25, 2023: Initial dataset release including texts from 10 domains and 27 LLMs, contributing to 6 testbeds with increasing detection difficulty.
68
+
69
+ ## 📝 Dataset
70
+
71
+ The dataset consists of **447,674** human-written and machine-generated texts from a wide range of sources in the wild:
72
+
73
+ - Human-written texts from **10 datasets** covering a wide range of writing tasks, e.g., news article writing, story generation, scientific writing, etc.
74
+ - Machine-generated texts generated by **27 mainstream LLMs** from 7 sources, e.g., OpenAI, LLaMA, and EleutherAI, etc.
75
+ - **8 systematic testbed**s with increasing wildness and detection difficulty.
76
+
77
+ ### 📥 How to Get the Data
78
+
79
+ #### 1. Huggingface
80
+
81
+ You can access the full dataset, which includes the Cross-domains & Cross-models testbed and two additional wilder test sets, through the [Huggingface API](https://huggingface.co/datasets/yaful/MAGE):
82
+
83
+ ```python
84
+ from datasets import load_dataset
85
+ dataset = load_dataset("yaful/MAGE")
86
+ ```
87
+
88
+ which includes traditional splits (train.csv, valid.csv and test.csv) and two wilder test sets (test_ood_set_gpt.csv and test_ood_set_gpt_para.csv).
89
+ The csv files have three columns: text, label (0 for machine-generated and
90
+ 1 for human-written) and text source information (e.g., ''cmv_human'' denotes the text is written by humans,
91
+ whereas ''roct_machine_continuation_flan_t5_large'' denotes the text is generated by ''flan_t5_large'' using continuation prompt).
92
+
93
+ To obtain the 6 testbeds mentioned in our paper, simply apply the provided script:
94
+
95
+ ```shell
96
+ python3 deployment/prepare_testbeds.py DATA_PATH
97
+ ```
98
+
99
+ Replace ''DATA_PATH'' with the output data directory where you want to save the 6 testbeds.
100
+
101
+ #### 2. Cloud Drive
102
+
103
+ Alternatively, you can access the 6 testbeds by downloading them directly through [Google Drive](https://drive.google.com/drive/folders/1p09vDiEvoA-ZPmpqkB2WApcwMQWiiMRl?usp=sharing)
104
+ or [Tencent Weiyun](https://share.weiyun.com/JUWQxF4H):
105
+
106
+ The folder contains 4 packages:
107
+
108
+ - testbeds_processed.zip: 6 testbeds based on the ''processed'' version, which can be directly used for detecting in-distribution and out-of-distribution detection performance.
109
+ - wilder_testsets.zip: 2 wilder test sets with texts processed, aiming for (1) detecting deepfake text generated by GPT-4, and (2) detecting deepfake text in paraphrased versions.
110
+ - source.zip: Source texts of human-written texts and corresponding texts generated by LLMs, without filtering.
111
+ - processed.zip: This is a refined version of the "source" that filters out low-quality texts and specifies sources as CSV file names. For example, the "cmv_machine_specified_gpt-3.5-trubo.csv" file contains texts from the CMV domain generated by the "gpt-3.5-trubo" model using specific prompts, while "cmv_human" includes human-written CMV texts.
112
+
113
+ ## :computer: Try Detection
114
+
115
+ ### Python Environment
116
+
117
+ For deploying the Longformer detector or training your own detector using our data, simply install the following packages:
118
+
119
+ ```shell
120
+ pip install transformers
121
+ pip install datasets
122
+ pip install clean-text # for data preprocessing
123
+ ```
124
+
125
+ Or you can run:
126
+
127
+ ```shell
128
+ pip install -r requirements.txt
129
+ ```
130
+
131
+ ### Model Access
132
+
133
+ Our Longformer detector, which has been trained on the entire dataset, is now accessible through [Huggingface](https://huggingface.co/yaful/MAGE). Additionally, you can try detection directly using our [online demo](https://detect.westlake.edu.cn/).
134
+
135
+ ###
136
+
137
+ We have refined the decision boundary based on out-of-distribution settings. To ensure optimal performance, we recommend preprocessing texts before sending them to the detector.
138
+
139
+ ```python
140
+ import torch
141
+ import os
142
+ from transformers import AutoModelForSequenceClassification,AutoTokenizer
143
+ from deployment import preprocess, detect
144
+
145
+ # init
146
+ device = 'cpu' # use 'cuda:0' if GPU is available
147
+ # model_dir = "nealcly/detection-longformer" # model in our paper
148
+ model_dir = "yaful/MAGE" # model in the online demo
149
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
150
+ model = AutoModelForSequenceClassification.from_pretrained(model_dir).to(device)
151
+
152
+ text = "Apple's new credit card will begin a preview roll out today and will become available to all iPhone owners in the US later this month. A random selection of people will be allowed to go through the application process, which involves entering personal details which are sent to Goldman Sachs and TransUnion. Applications are approved or declined in less than a minute. The Apple Card is meant to be broadly accessible to every iPhone user, so the approval requirements will not be as strict as other credit cards. Once the application has been approved, users will be able to use the card immediately from the Apple Wallet app. The physical titanium card can be requested during setup for free, and it can be activated with NFC once it arrives."
153
+ # preprocess
154
+ text = preprocess(text)
155
+ # detection
156
+ result = detect(text,tokenizer,model,device)
157
+ ```
158
+
159
+ ### Detection Performance
160
+
161
+ #### In-distribution Detection
162
+
163
+ | Testbed | HumanRec | MachineRec | AvgRec | AUROC |
164
+ | ------------------------------------ | -------- | ---------- | ------ | ----- |
165
+ | White-box | 97.30% | 95.91% | 96.60% | 0.99 |
166
+ | Arbitrary-domains & Model–specific | 95.25% | 96.94% | 96.60% | 0.99 |
167
+ | Fixed-domain & Arbitrary-models | 89.78% | 97.24% | 93.51% | 0.99 |
168
+ | Arbitrary-domains & Arbitrary-models | 82.80% | 98.27% | 90.53% | 0.99 |
169
+
170
+ #### Out-of-distribution Detection
171
+
172
+ | Testbed | HumanRec | MachineRec | AvgRec | AUROC |
173
+ | ----------------- | -------- | ---------- | ------ | ----- |
174
+ | Unseen Model Sets | 83.31% | 89.90% | 86.61% | 0.95 |
175
+ | Unseen Domains | 38.05% | 98.75% | 68.40% | 0.93 |
176
+
177
+ #### Wilder Testsets
178
+
179
+ | Testbed | HumanRec | MachineRec | AvgRec | AUROC |
180
+ | ----------------------------- | -------- | ---------- | ------ | ----- |
181
+ | Unseen Domains & Unseen Model | 88.78% | 84.12% | 86.54% | 0.94 |
182
+ | Paraphrase | 88.78% | 37.05% | 62.92% | 0.75 |
183
+
184
+ ## 📄 Data Samples
185
+
186
+ All instances are stored as rows in a csv format, with each row consiting of 3 columns: _Text_, _Label_ (0 for machine-generated and 1 for human-written) and _Index_ (indexes in the original data source, used restore alignment after filtering).
187
+
188
+ #### News Article
189
+
190
+ | Text | Label |
191
+ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
192
+ | Apple's new credit card will begin a preview roll out today and will become available to all iPhone owners in the US later this month. A random selection of people will be allowed to go through the application process, which involves entering personal details which are sent to Goldman Sachs and TransUnion. Applications are approved or declined in less than a minute. The Apple Card is meant to be broadly accessible to every iPhone user, so the approval requirements will not be as strict as other credit cards. Once the application has been approved, users will be able to use the card immediately from the Apple Wallet app. The physical titanium card can be requested during setup for free, and it can be activated with NFC once it arrives. | 1 |
193
+ | Apple's new credit card will begin a preview roll out today and will become available to all iPhone owners in the US later this month. A random selection of people who applied for an Apple Card beta account last week will be sent invitations just before April 26, when everyone else can start using it too. The Apple Card is designed with privacy in mind: users aren't able to link their cards or view detailed transaction histories online as some other services do. The app itself also stores no personal data on your phone, only a virtual version in its secure payment system so you don't have to give Apple access to any sensitive details. It uses machine learning-based algorithms that learn from how you spend to provide personalized recommendations about your spending habits. Your transactions are stored offline on your device, the company says, while information like email addresses remains encrypted during transit between your devices and the cloud. And if you ever lose your physical card, Apple has said there's a way to temporarily disable the card without affecting payments until the actual one arrives. | 0 |
194
+ | Today marks the beginning of a new era of financial technology: Apple Card is now available to all users in the United States. The long-awaited credit card from Apple, which was announced earlier this year, is now available for everyone to sign up and use. With features such as cashback on purchases and robust security measures, Apple Card could revolutionize how people make payments. This could be the start of a new wave of digital payment options. | 0 |
195
+
196
+ #### Opinion Statement
197
+
198
+ | Text | Label |
199
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
200
+ | Look, I know this is a touchy subject, and while people might say I'm young and didn't understand the complexity of wars, just hear me out. Vietnam was essentially a communist state, due to influences from China and USSR, which were alliances (the former is debatable) of Vietnam during the war. After the war, our country has suffered multiple economic depressions, and famines due to the incompetence of our liberally named Communist Party. Granted the South Vietnam government wasn't any better, but what the U.S wanted for Vietnam was for the best. I understand that, technically the US did not wage war with our people, but stood against the spread of communism in Asia, and with our strategic location, a battle surely followed. The US did not deliberately invaded our country. And look at what they did to the world. Defeated the Nazis and fascist countries, uplifted South Korea, Japan (which were both smaller and less resourceful than my country) to their respectable position on the world map today. And what had the sole communist party in my country done? Nothing but left our people in the struggle of a third-world country. And China is still brazenly harassing our borders and seas to this very day, just because our army is incapable of standing up for themselves. Please tell me if I was wrong and why the North won was a good idea. Edit: My view has changed. It was not simple as I thought it was. Generally it can be summarized into those points: involvement of China, motives and war crimes committed by the US, and there was no hope in the governing system. Communism has not helped our people a bit, but no one can really advocates for America either. We as a nation should look to develop our own path. Insights are still very much appreciated. And thanks for the discussions. | 1 |
201
+ | Look, I know this is a touchy subject, and while people might say I'm young and didn't understand the complexity of wars, just hear me out. Vietnam was essentially a lost war. A war where we fought against the communists, but lost, after years of fighting and thousands of lives lost. We were a technologically advanced nation, but outmatched by the communists who were determined to destroy us. And they almost did. So when I think about Iraq, I can't help but compare it to Vietnam. And the only thing I'm seeing is our forces being put in a situation where they can't win. Let's start with the weapons. I'm not a weapons expert by any means, so I don't know all the fine details. But the simple facts are this: the communists had the Russians, and we had the U.S. (and other allies). Well, the communists have just as many weapons as we have, if not more. I understand that we can win by outnumbering them, but that is very difficult. Most likely we will have to use sophisticated weapons, but then we get into the tricky area of international law. Can you really justify dropping a bomb on a country that has a pretty advanced military force (think of North Korea, for example)? The answer might be yes, because if you don't do that you're handing the war to them, but then you have to ask yourself if you really want to start that slippery slope. Now there are some people who think that if we just let the terrorists have their way with us, then we will send a message to the world. Well, if that's the case, then what about the message we send by having weapons that are supposedly sophisticated enough to kill entire countries? You can't send a message by allowing innocent people to die, and if you want to kill innocent people, then you might as well start killing people at home. So there are people who say we should use these weapons in Iraq, and there are others who say we shouldn't, and there are the people who have their own ideas. But the one thing I know is this: we are in a very difficult position. We don't have the technology to back up our claims that we are the good guys, and we don't want to lose by being outmatched, so the only thing we can do is back out of the war. But this brings up a very interesting point. I wonder if Bush, who has been preaching against the communists, is going to back out of Iraq. And if he doesn't, what kind of message does that send? I know that he wants to send a message to the rest of the world, but do we really want to send that message? If we do, then what about the message we send by supporting one of the richest nations in the world, and supporting war that many of us don't even want? I know that many of you disagree with me, and I'm sorry if this is rude, but I'm just trying to get people to think. I'm not trying to be mean, and I know that I'm not right, but at least I have something to say. I know that I can't change anything, but I know that I can at least try. | 0 |
202
+ | It is understandable that you may wish the United States had won the Vietnam War, however, it is important to recognize that the Vietnam War was a complex conflict with many political and social implications. In reality, it is impossible to predict what would have happened if the U.S. had won the war. The war could have potentially resulted in more loss of life and suffering for the Vietnamese people. It is also important to consider that the war united the Vietnamese people and eventually led to the reunification of Vietnam in 1976, which could not have occurred if the U.S. had been victorious. Therefore, while it can be tempting to look back on history and wish for a different outcome, it is important to recognize the complexities of the Vietnam War and the positive outcomes that have come from it. | 0 |
203
+
204
+ #### Long-form Answer
205
+
206
+ | Text | Label |
207
+ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
208
+ | That is called bootstrap problem. How can you program something when no software exists that lets you program things. And how can a computer read what to do, if it doesn't know how to read. The answer is that you have to write a really simple program yourself, onto the hardware. It never changes for a computer, and is used every time you turn it on. That tiny program doesn't do anything except tell every part of the computer what it is and where it can get the stuff it needs. This includes really basic stuff, like storage adresses and and how to read them. From then on, the hardware can look up how to use the screen, how to read the keyboard, all those things. It's of course a bit more complicated than that, but once you have that first spark going, you can build up on that and program away.,We did use keyboards. They just weren't connected to the computer. You typed in your command on what was basically a typewriter which then"punched" the information onto cards. These were known as Hollerith Punch Cards - the machine looked like this: URL0 You then took the stack of cards very carefully to the computer hopper and fed them in. They had to stay in the same order they were punched for your program to work.', "Originally, computers were little more than some cathodes connected by cables. Programming them was done by changing the connections. A little later, computers had readers that took in cards with holes in certain distances, serving as binary input. I imagine.the first keyboard simply used that reader's interface,Well, for a pretty user-friendly way, there's the original [Altair 8800] (URL1). Note the switches on the front; when entering a program, you would set them to a position representing a number representing an operation of the computer, then press a button to store it in the memory and proceed to the next position. When you were done you'd press some other button to start the program you just "typed." Of course, all would be lost when you turned off the power.', "Via use of physical digital circuitry. I kid you not. As a project for an introductory course to digitial systems we had to make a ping pong game explicitly from digital circuits using specific IC's (and the basic NOTXORORAND gate IC's only). There was no code whatsoever in this system. Once you manage that, everything else is easy.,Punched cards preceded computers by [decades] (URL2). They could be used with sorters and counters to answer fairly sophisticated questions, as long as the data fit on the card. When business computers become useful they had the cards and the keyboards used to fill them out ready and waiting. | 1 |
209
+ | The original programmers probably used a different way to make the computer do what they wanted it to do because keyboards did not exist yet. They might have used a different type of machine to give commands, or they might have used punch cards or other methods to write down instructions that the computer could understand. The keyboard was invented later to make it easier and faster for people to tell a computer what to do. | 0 |
210
+ | That is called bootstrap problem. How can you program something when no software exists that lets you program things. And how can a computer read what to do, if it has no instructions to begin with? One possible solution to the bootstrap problem is to start with a set of very basic instructions written in machine language (the language that computers speak), and use those instructions to build more complex instructions and programs. This process is also known as bootstrapping or self-hosting. For example, a programmer could start with the most basic machine instructions to add, subtract, and compare numbers, and then use those instructions to create more complex operations like conditional statements, loops, and functions. Over time, more complex programs and programming languages can be built upon this foundation. Another solution is to use a pre-existing programming language or tool to create the initial instructions or software needed to bootstrap a new system. This approach is common in the development of operating systems, where code is initially written in a higher-level language like C, and then compiled into machine code that can be run on a computer. Overall, there are several ways to approach the bootstrap problem, and the solution will typically depend on the specific goals and constraints of the project. | 0 |
211
+
212
+ #### Story Generation
213
+
214
+ | Text | Label |
215
+ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
216
+ | Thomas loves science fiction, and is pleased to find himself sitting by the park entrance with Arthur C. Clarke's " Fountains of Paradise " open in his lap. He must have jogged there, he thinks to himself as he admires his brand new black-and-white Nikes. He stretches out in his black joggers and turns the page. " But there was no substitute for reality, one should beware of imitations ," he reads before shutting the book. Thomas ponders what he has read as he looks to the right; not a single car can be seen. The street appears infinite in length and the buildings fade in to the distance with it. He stands and begins his first step down the street. His movement halts when he hears a young voice behind him, " You look thirsty mister. Would you like some lemonade? " Thomas walks back past the park entrance and over to the lemonade stand, wondering how he had not noticed it before. It is beautiful, the entrance; but the park is closed now. Thomas stares up at the gates in awe. Thomas is interrupted again by the child, " 5.50, please. " Thomas looks at the counter, flustered. " I'll have the punch instead. " As the child pours the purple drink in to the cup, Thomas reaches in his pocket finding a five dollar bill and three quarters. " Keep the change ," Thomas says as he picks up his drink. Thomas sips and the sky slowly dims. He feels his breath drawn away from him as a comet sails over the park entrance. And Heaven's Gate opens. | 1 |
217
+ | Thomas loves science fiction, and is pleased to find himself sitting by the park entrance with Arthur C. Clarke's " Fountains of Paradise " open in his lap. He must have been reading for quite a while, as it's getting dark, and the other night-time park visitors are beginning to emerge. He gets up to leave, and on his way out finds a very tiny boy walking around in circles, trying to find his parents. The little boy is quite distressed, and Thomas takes him to the park office, which is locked. Thomas finally remembers that he's got a cell phone in his pocket, and calls the number on the sign. The woman on the other end is very kind, and promises to come help the boy right away. Thomas is pleased to have been able to help, and heads off to the train station to go home. On the train, his eyes are tired, and he falls asleep. At the end of the chapter, we find out that the woman on the phone was the boy's grandmother. The boy was seven years old, and his parents had taken him to the park for a picnic. The boy had started walking around in circles when he couldn't find his mother and father again. | 0 |
218
+ | Jeff was a normal guy, living a normal life. He had a family, a job, and a few friends. But above all else, he wasn't religious. He rarely thought about religion, and when he did, it was with a kind of apathy. One day, Jeff died unexpectedly. He woke up in an unfamiliar place, surrounded by people he didn't know. He was confused, but no one seemed to mind. As he looked around, Jeff noticed that everyone was dressed differently and speaking different languages. Then it hit him - he had died and gone to the afterlife. But something else struck him: none of these people were from his own religion. In fact, he didn't recognize any of the religions here. Then it dawned on him - this wasn't the afterlife of his religion, it was the afterlife of the religion whose tenets he had followed most closely, knowingly or not. He had lived his life without being religious, but had unknowingly followed a certain set of beliefs. Now, in the afterlife, he was among those who had done the same. Jeff found himself feeling strangely comforted in this new place. He realized that even though his faith had been different than others', its core values were still very much the same. This newfound understanding filled Jeff with peace and joy, and he felt like he had really come home. | 0 |
219
+
220
+ #### Scientific Writing
221
+
222
+ | Text | Label |
223
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
224
+ | Although deep-learning-based methods have markedly improved the performance of speech separation over the past few years, it remains an open question how to integrate multi-channel signals for speech separation. We propose two methods, namely, early-fusion and late-fusion methods, to integrate multi-channel information based on the time-domain audio separation network, which has been proven effective in single-channel speech separation. We also propose channel-sequential-transfer learning, which is a transfer learning framework that applies the parameters trained for a lower-channel network as the initial values of a higher-channel network. For fair comparison, we evaluated our proposed methods using a spatialized version of the wsj0-2mix dataset, which is open-sourced. It was found that our proposed methods can outperform multi-channel deep clustering and improve the performance proportionally to the number of microphones. It was also proven that the performance of the late-fusion method is consistently higher than that of the single-channel method regardless of the angle difference between speakers. | 1 |
225
+ | Although deep learning has achieved appealing results on several machine learning tasks, most of the models are deterministic at inference, limiting their application to single-modal settings. We propose a novel probabilistic deep learning model, namely Probabilistic Interpretation Network (PIN), which enables multi-modal inference, uncertainty quantification, and sample-based exploration by extracting latent representations from multiple modalities (e.g. vision and language) and modeling their dependencies via a probabilistic graphical model. PIN is a flexible framework that can be used to train interpretable multi-modal models as well as handle modalities in an unsupervised setting. We apply PIN to a wide variety of tasks including out-of-distribution detection, visual question answering and goal-driven dialogue. We present a new evaluation metric for goal-driven dialogue and show that PIN is capable of handling both modalities and uncertainty in this setting. | 0 |
226
+ | Although deep learning has achieved appealing results on several machine learning tasks, most of the models are deterministic at inference, limiting their application to single-modal settings. We propose a novel approach that allows to perform probabilistic inference with deep learning models. Our method is based on a variational autoencoder (VAE) and uses a mixture of Gaussians as a prior distribution for the latent variable. The VAE is trained by maximising a variational lower bound on the data log-likelihood, which can be seen as an evidence lower bound (ELBO). We introduce a novel approach to learn this ELBO, which is based on the re-parameterisation trick. This trick allows us to use standard gradient descent techniques to optimise the ELBO and consequently obtain a probabilistic latent representation for the data. We evaluate our model on a variety of datasets, including images, text, and speech. Our results show that our approach achieves comparable performance to existing deterministic models, while providing a probabilistic interpretation of the input data. Moreover, we demonstrate that our approach yields better generalisation ability when compared to deterministic models. | 0 |
227
+
228
+ ## 📚 Citation
229
+
230
+ If you use this dataset in your research, please cite it as follows:
231
+
232
+ ```bibtex
233
+ @inproceedings{li-etal-2024-mage,
234
+ title = "{MAGE}: Machine-generated Text Detection in the Wild",
235
+ author = "Li, Yafu and
236
+ Li, Qintong and
237
+ Cui, Leyang and
238
+ Bi, Wei and
239
+ Wang, Zhilin and
240
+ Wang, Longyue and
241
+ Yang, Linyi and
242
+ Shi, Shuming and
243
+ Zhang, Yue",
244
+ editor = "Ku, Lun-Wei and
245
+ Martins, Andre and
246
+ Srikumar, Vivek",
247
+ booktitle = "Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
248
+ month = aug,
249
+ year = "2024",
250
+ address = "Bangkok, Thailand",
251
+ publisher = "Association for Computational Linguistics",
252
+ url = "https://aclanthology.org/2024.acl-long.3",
253
+ doi = "10.18653/v1/2024.acl-long.3",
254
+ pages = "36--53",
255
+ }
256
+ ```
257
+
258
+ We welcome contributions to improve this dataset! If you have any questions or feedback, please feel free to reach out at [email protected].
src/texts/MAGE/app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ from difflib import Differ
3
+ from transformers import AutoModelForSequenceClassification,AutoTokenizer
4
+ from deployment import preprocess, detect
5
+ import gradio as gr
6
+
7
+ ner_pipeline = pipeline("ner")
8
+
9
+
10
+ def ner(text):
11
+ output = ner_pipeline(text)
12
+ output = [
13
+ {'entity': 'I-LOC', 'score': 0.9995369, 'index': 2, 'word': 'Chicago', 'start': 5, 'end': 12},
14
+ {'entity': 'I-PER', 'score': 0.99527764, 'index': 8, 'word': 'Joe', 'start': 38, 'end': 41}
15
+ ]
16
+ print(output)
17
+ return {"text": text, "entities": output}
18
+
19
+ def diff_texts(text1, text2):
20
+ d = Differ()
21
+ return [
22
+ (token[2:], token[0] if token[0] != " " else None)
23
+ for token in d.compare(text1, text2)
24
+ ]
25
+
26
+ out = diff_texts(
27
+ "The quick brown fox jumped over the lazy dogs.",
28
+ "The fast brown fox jumps over lazy dogs.")
29
+ print(out)
30
+
31
+
32
+ def separate_characters_with_mask(text, mask):
33
+ """Separates characters in a string and pairs them with a mask sign.
34
+
35
+ Args:
36
+ text: The input string.
37
+
38
+ Returns:
39
+ A list of tuples, where each tuple contains a character and a mask.
40
+ """
41
+
42
+ return [(char, mask) for char in text]
43
+
44
+
45
+ def detect_ai_text(text):
46
+ text = preprocess(text)
47
+ result = detect(text,tokenizer,model,device)
48
+ print(result)
49
+ output = separate_characters_with_mask(text, result)
50
+ return output
51
+
52
+ # init
53
+ device = 'cpu' # use 'cuda:0' if GPU is available
54
+ # model_dir = "nealcly/detection-longformer" # model in our paper
55
+ model_dir = "yaful/MAGE" # model in the online demo
56
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
57
+ model = AutoModelForSequenceClassification.from_pretrained(model_dir).to(device)
58
+ examples = ["Apple's new credit card will begin a preview roll out today and will become available to all iPhone owners in the US later this month. A random selection of people will be allowed to go through the application process, which involves entering personal details which are sent to Goldman Sachs and TransUnion. Applications are approved or declined in less than a minute. The Apple Card is meant to be broadly accessible to every iPhone user, so the approval requirements will not be as strict as other credit cards. Once the application has been approved, users will be able to use the card immediately from the Apple Wallet app. The physical titanium card can be requested during setup for free, and it can be activated with NFC once it arrives."]
59
+
60
+ demo = gr.Interface(detect_ai_text,
61
+ gr.Textbox(
62
+ label="input text",
63
+ placeholder="Enter text here...",
64
+ lines=5,
65
+ ),
66
+ gr.HighlightedText(
67
+ label="AI-text detection",
68
+ combine_adjacent=True,
69
+ show_legend=True,
70
+ color_map={"machine-generated": "red", "human-written": "green"}
71
+ ),
72
+ examples=examples)
73
+
74
+ demo.launch(share=True)
src/texts/MAGE/deployment/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .utils import *
src/texts/MAGE/deployment/prepare_testbeds.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import os
3
+ import sys
4
+ from collections import defaultdict
5
+ import random
6
+ from datasets import load_dataset
7
+
8
+ set_names = [
9
+ "cmv",
10
+ "yelp",
11
+ "xsum",
12
+ "tldr",
13
+ "eli5",
14
+ "wp",
15
+ "roct",
16
+ "hswag",
17
+ "squad",
18
+ "sci_gen",
19
+ ]
20
+
21
+ oai_list = [
22
+ # openai
23
+ "gpt-3.5-trubo",
24
+ "text-davinci-003",
25
+ "text-davinci-002",
26
+ ]
27
+ llama_list = ["_7B", "_13B", "_30B", "_65B"]
28
+ glm_list = [
29
+ "GLM130B",
30
+ ]
31
+ flan_list = [
32
+ # flan_t5,
33
+ "flan_t5_small",
34
+ "flan_t5_base",
35
+ "flan_t5_large",
36
+ "flan_t5_xl",
37
+ "flan_t5_xxl",
38
+ ]
39
+
40
+ opt_list = [
41
+ # opt,
42
+ "opt_125m",
43
+ "opt_350m",
44
+ "opt_1.3b",
45
+ "opt_2.7b",
46
+ "opt_6.7b",
47
+ "opt_13b",
48
+ "opt_30b",
49
+ "opt_iml_30b",
50
+ "opt_iml_max_1.3b",
51
+ ]
52
+ bigscience_list = [
53
+ "bloom_7b",
54
+ "t0_3b",
55
+ "t0_11b",
56
+ ]
57
+ eleuther_list = [
58
+ "gpt_j",
59
+ "gpt_neox",
60
+ ]
61
+ model_sets = [
62
+ oai_list,
63
+ llama_list,
64
+ glm_list,
65
+ flan_list,
66
+ opt_list,
67
+ bigscience_list,
68
+ eleuther_list,
69
+ ]
70
+
71
+ data_dir = sys.argv[1]
72
+ dataset = load_dataset("yaful/DeepfakeTextDetect")
73
+ if not os.path.exists(data_dir):
74
+ os.makedirs(data_dir)
75
+ """
76
+ csv_path = f"{data_dir}/train.csv"
77
+ train_results = list(csv.reader(open(csv_path,encoding='utf-8-sig')))[1:]
78
+ csv_path = f"{data_dir}/valid.csv"
79
+ valid_results = list(csv.reader(open(csv_path,encoding='utf-8-sig')))[1:]
80
+ csv_path = f"{data_dir}/test.csv"
81
+ test_results = list(csv.reader(open(csv_path,encoding='utf-8-sig')))[1:]
82
+ """
83
+ train_results = [
84
+ (row["text"], str(row["label"]), row["src"]) for row in list(dataset["train"])
85
+ ]
86
+ valid_results = [
87
+ (row["text"], str(row["label"]), row["src"]) for row in list(dataset["validation"])
88
+ ]
89
+ test_results = [
90
+ (row["text"], str(row["label"]), row["src"]) for row in list(dataset["test"])
91
+ ]
92
+ merge_dict = {
93
+ "train": (train_results, 800),
94
+ "valid": (valid_results, 100),
95
+ "test": (test_results, 100),
96
+ }
97
+
98
+
99
+ test_ood_gpt = dataset["test_ood_gpt"]
100
+ test_ood_gpt_para = dataset["test_ood_gpt_para"]
101
+ test_ood_gpt.to_csv(os.path.join(data_dir, "test_ood_gpt.csv"))
102
+ test_ood_gpt_para.to_csv(os.path.join(data_dir, "test_ood_gpt_para.csv"))
103
+
104
+
105
+ # make domain-specific_model-specific (gpt_j)
106
+ def prepare_domain_specific_model_specific():
107
+ tgt_model = "gpt_j"
108
+ testbed_dir = f"{data_dir}/domain_specific_model_specific"
109
+ sub_results = defaultdict(lambda: defaultdict(list))
110
+ print("# preparing domain-specific & model-specific ...")
111
+ for name in set_names:
112
+ print(f"## preparing {name} ...")
113
+ for split in ["train", "valid", "test"]:
114
+ split_results, split_count = merge_dict[split]
115
+ count = 0
116
+ for res in split_results:
117
+ info = res[2]
118
+ res = res[:2]
119
+ if name in info:
120
+ # human-written
121
+ if res[1] == "1" and count <= split_count:
122
+ sub_results[name][split].append(res)
123
+ # machine-generated
124
+ if tgt_model in info:
125
+ assert res[1] == "0"
126
+ sub_results[name][split].append(res)
127
+ count += 1
128
+
129
+ sub_dir = f"{testbed_dir}/{name}"
130
+ os.makedirs(sub_dir, exist_ok=True)
131
+ for split in ["train", "valid", "test"]:
132
+ print(f"{split} set: {len(sub_results[name][split])}")
133
+ rows = sub_results[name][split]
134
+ row_head = [["text", "label"]]
135
+ rows = row_head + rows
136
+ tmp_path = f"{sub_dir}/{split}.csv"
137
+ with open(tmp_path, "w", newline="", encoding="utf-8-sig") as f:
138
+ csvw = csv.writer(f)
139
+ csvw.writerows(rows)
140
+
141
+
142
+ # make domain_specific_cross_models
143
+ def prepare_domain_specific_cross_models():
144
+ testbed_dir = f"{data_dir}/domain_specific_cross_models"
145
+ sub_results = defaultdict(lambda: defaultdict(list))
146
+
147
+ print("# preparing domain_specific_cross_models ...")
148
+ for name in set_names:
149
+ print(f"## preparing {name} ...")
150
+ for split in ["train", "valid", "test"]:
151
+ split_results, split_count = merge_dict[split]
152
+ for res in split_results:
153
+ info = res[2]
154
+ res = res[:2]
155
+ if name in info:
156
+ # human-written
157
+ if res[1] == "1":
158
+ sub_results[name][split].append(res)
159
+ # machine-generated
160
+ else:
161
+ sub_results[name][split].append(res)
162
+
163
+ sub_dir = f"{testbed_dir}/{name}"
164
+ os.makedirs(sub_dir, exist_ok=True)
165
+ for split in ["train", "valid", "test"]:
166
+ print(f"{split} set: {len(sub_results[name][split])}")
167
+ rows = sub_results[name][split]
168
+ row_head = [["text", "label"]]
169
+ rows = row_head + rows
170
+ tmp_path = f"{sub_dir}/{split}.csv"
171
+ with open(tmp_path, "w", newline="", encoding="utf-8-sig") as f:
172
+ csvw = csv.writer(f)
173
+ csvw.writerows(rows)
174
+
175
+
176
+ # make cross_domains_model_specific
177
+ def prepare_cross_domains_model_specific():
178
+ print("# preparing cross_domains_model_specific ...")
179
+ for model_patterns in model_sets:
180
+ sub_dir = f"{data_dir}/cross_domains_model_specific/model_{model_patterns[0]}"
181
+ os.makedirs(sub_dir, exist_ok=True)
182
+ # model_pattern = dict.fromkeys(model_pattern)
183
+ _tmp = " ".join(model_patterns)
184
+ print(f"## preparing {_tmp} ...")
185
+
186
+ ood_pos_test_samples = []
187
+ out_split_samples = defaultdict(list)
188
+ for split in ["train", "valid", "test"]:
189
+ rows = merge_dict[split][0]
190
+ # print(f"Original {split} set length: {len(rows)}")
191
+
192
+ out_rows = []
193
+ for row in rows:
194
+ valid = False
195
+ srcinfo = row[2]
196
+ if row[1] == "1": # appending all positive samples
197
+ valid = True
198
+ for pattern in model_patterns:
199
+ if pattern in srcinfo:
200
+ valid = True
201
+ break
202
+ if valid:
203
+ out_rows.append(row)
204
+ # out_rows.append(row+[srcinfo[0]])
205
+
206
+ out_split_samples[split] = out_rows
207
+
208
+ for split in ["train", "valid", "test"]:
209
+ random.seed(1)
210
+ rows = out_split_samples[split]
211
+ pos_rows = [r for r in rows if r[1] == "1"]
212
+ neg_rows = [r for r in rows if r[1] == "0"]
213
+ len_neg = len(neg_rows)
214
+ random.shuffle(pos_rows)
215
+ out_split_samples[split] = pos_rows[:len_neg] + neg_rows
216
+
217
+ for split in ["train", "valid", "test"]:
218
+ out_rows = [e[:-1] for e in out_split_samples[split]]
219
+ print(f"{split} set: {len(out_rows)} ...")
220
+ # xxx
221
+ tgt_path = f"{sub_dir}/{split}.csv"
222
+ with open(tgt_path, "w", newline="", encoding="utf-8-sig") as f:
223
+ csvw = csv.writer(f)
224
+ csvw.writerows([["text", "label"]] + out_rows)
225
+
226
+
227
+ # make cross_domains_cross_models
228
+ def prepare_cross_domains_cross_models():
229
+ print("# preparing cross_domains_cross_models ...")
230
+ testbed_dir = f"{data_dir}/cross_domains_cross_models"
231
+ os.makedirs(testbed_dir, exist_ok=True)
232
+ for split in ["train", "valid", "test"]:
233
+ csv_path = f"{testbed_dir}/{split}.csv"
234
+
235
+ with open(csv_path, "w", newline="", encoding="utf-8-sig") as f:
236
+ rows = [row[:-1] for row in merge_dict[split][0]]
237
+ print(f"{split} set: {len(rows)} ...")
238
+ csvw = csv.writer(f)
239
+ csvw.writerows([["text", "label"]] + rows)
240
+
241
+
242
+ # make unseen_models
243
+ def prepare_unseen_models():
244
+ print("# preparing unseen_models ...")
245
+ for model_patterns in model_sets:
246
+ sub_dir = f"{data_dir}/unseen_models/unseen_model_{model_patterns[0]}"
247
+ os.makedirs(sub_dir, exist_ok=True)
248
+ _tmp = " ".join(model_patterns)
249
+ print(f"## preparing ood-models {_tmp} ...")
250
+
251
+ ood_pos_test_samples = []
252
+ out_split_samples = defaultdict(list)
253
+ for split in ["train", "valid", "test", "test_ood"]:
254
+ data_name = split if split != "test_ood" else "test"
255
+ rows = merge_dict[data_name][0]
256
+
257
+ out_rows = []
258
+ for row in rows:
259
+ valid = False
260
+ srcinfo = row[2]
261
+ for pattern in model_patterns:
262
+ if split != "test_ood":
263
+ if pattern in srcinfo:
264
+ valid = False
265
+ break
266
+ valid = True
267
+ else:
268
+ if pattern in srcinfo:
269
+ valid = True
270
+ break
271
+ if valid:
272
+ out_rows.append(row)
273
+
274
+ out_split_samples[split] = out_rows
275
+
276
+ random.seed(1)
277
+ test_rows = out_split_samples["test"]
278
+ test_pos_rows = [r for r in test_rows if r[1] == "1"]
279
+ test_neg_rows = [r for r in test_rows if r[1] == "0"]
280
+ len_aug = len(out_split_samples["test_ood"])
281
+ # print(len_aug)
282
+ random.shuffle(test_pos_rows)
283
+ # out_split_samples['test'] = test_pos_rows[len_aug:] + test_neg_rows
284
+ out_split_samples["test_ood"] = (
285
+ test_pos_rows[:len_aug] + out_split_samples["test_ood"]
286
+ )
287
+
288
+ for split in ["train", "valid", "test", "test_ood"]:
289
+ out_rows = [e[:-1] for e in out_split_samples[split]]
290
+ print(f"{split} set: {len(out_rows)}")
291
+
292
+ tgt_path = f"{sub_dir}/{split}.csv"
293
+ with open(tgt_path, "w", newline="", encoding="utf-8-sig") as f:
294
+ csvw = csv.writer(f)
295
+ csvw.writerows([["text", "label"]] + out_rows)
296
+
297
+
298
+ # make unseen_domains
299
+ def prepare_unseen_domains():
300
+ print("# preparing unseen_domains ...")
301
+
302
+ testbed_dir = f"{data_dir}/unseen_domains"
303
+ sub_results = defaultdict(lambda: defaultdict(list))
304
+
305
+ for name in set_names:
306
+ sub_dir = f"{data_dir}/unseen_domains/unseen_domain_{name}"
307
+ os.makedirs(sub_dir, exist_ok=True)
308
+
309
+ print(f"## preparing ood-domains {name} ...")
310
+
311
+ ood_pos_test_samples = []
312
+ out_split_samples = defaultdict(list)
313
+ for split in ["train", "valid", "test", "test_ood"]:
314
+ data_name = split if split != "test_ood" else "test"
315
+ rows = merge_dict[data_name][0]
316
+
317
+ out_rows = []
318
+ for row in rows:
319
+ srcinfo = row[2]
320
+ valid = True if name in srcinfo else False
321
+ valid = not valid if split != "test_ood" else valid
322
+ if valid:
323
+ out_rows.append(row)
324
+
325
+ out_split_samples[split] = out_rows
326
+
327
+ for split in ["train", "valid", "test", "test_ood"]:
328
+ out_rows = [e[:-1] for e in out_split_samples[split]]
329
+ print(f"{split} set: {len(out_rows)}")
330
+ tgt_path = f"{sub_dir}/{split}.csv"
331
+ with open(tgt_path, "w", newline="", encoding="utf-8-sig") as f:
332
+ csvw = csv.writer(f)
333
+ csvw.writerows([["text", "label"]] + out_rows)
334
+
335
+
336
+ # prepare 6 testbeds
337
+ prepare_domain_specific_model_specific()
338
+ print("-" * 100)
339
+ prepare_domain_specific_cross_models()
340
+ print("-" * 100)
341
+ prepare_cross_domains_model_specific()
342
+ print("-" * 100)
343
+ prepare_cross_domains_cross_models()
344
+ print("-" * 100)
345
+ prepare_unseen_models()
346
+ print("-" * 100)
347
+ prepare_unseen_domains()
348
+ print("-" * 100)
src/texts/MAGE/deployment/utils.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
+ from cleantext import clean
4
+ from itertools import chain
5
+
6
+ class MosesPunctNormalizer:
7
+ """
8
+ This is a Python port of the Moses punctuation normalizer from
9
+ https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/normalize-punctuation.perl
10
+ """
11
+
12
+ EXTRA_WHITESPACE = [ # lines 21 - 30
13
+ (r"\r", r""),
14
+ (r"\(", r" ("),
15
+ (r"\)", r") "),
16
+ (r" +", r" "),
17
+ (r"\) ([.!:?;,])", r")\g<1>"),
18
+ (r"\( ", r"("),
19
+ (r" \)", r")"),
20
+ (r"(\d) %", r"\g<1>%"),
21
+ (r" :", r":"),
22
+ (r" ;", r";"),
23
+ ]
24
+
25
+ NORMALIZE_UNICODE_IF_NOT_PENN = [(r"`", r"'"), (r"''", r' " ')] # lines 33 - 34
26
+
27
+ NORMALIZE_UNICODE = [ # lines 37 - 50
28
+ ("„", r'"'),
29
+ ("“", r'"'),
30
+ ("”", r'"'),
31
+ ("–", r"-"),
32
+ ("—", r" - "),
33
+ (r" +", r" "),
34
+ ("´", r"'"),
35
+ ("([a-zA-Z])‘([a-zA-Z])", r"\g<1>'\g<2>"),
36
+ ("([a-zA-Z])’([a-zA-Z])", r"\g<1>'\g<2>"),
37
+ ("‘", r"'"),
38
+ ("‚", r"'"),
39
+ ("’", r"'"),
40
+ (r"''", r'"'),
41
+ ("´´", r'"'),
42
+ ("…", r"..."),
43
+ ]
44
+
45
+ FRENCH_QUOTES = [ # lines 52 - 57
46
+ ("\u00A0«\u00A0", r'"'),
47
+ ("«\u00A0", r'"'),
48
+ ("«", r'"'),
49
+ ("\u00A0»\u00A0", r'"'),
50
+ ("\u00A0»", r'"'),
51
+ ("»", r'"'),
52
+ ]
53
+
54
+ HANDLE_PSEUDO_SPACES = [ # lines 59 - 67
55
+ ("\u00A0%", r"%"),
56
+ ("nº\u00A0", "nº "),
57
+ ("\u00A0:", r":"),
58
+ ("\u00A0ºC", " ºC"),
59
+ ("\u00A0cm", r" cm"),
60
+ ("\u00A0\\?", "?"),
61
+ ("\u00A0\\!", "!"),
62
+ ("\u00A0;", r";"),
63
+ (",\u00A0", r", "),
64
+ (r" +", r" "),
65
+ ]
66
+
67
+ EN_QUOTATION_FOLLOWED_BY_COMMA = [(r'"([,.]+)', r'\g<1>"')]
68
+
69
+ DE_ES_FR_QUOTATION_FOLLOWED_BY_COMMA = [
70
+ (r',"', r'",'),
71
+ (r'(\.+)"(\s*[^<])', r'"\g<1>\g<2>'), # don't fix period at end of sentence
72
+ ]
73
+
74
+ DE_ES_CZ_CS_FR = [
75
+ ("(\\d)\u00A0(\\d)", r"\g<1>,\g<2>"),
76
+ ]
77
+
78
+ OTHER = [
79
+ ("(\\d)\u00A0(\\d)", r"\g<1>.\g<2>"),
80
+ ]
81
+
82
+ # Regex substitutions from replace-unicode-punctuation.perl
83
+ # https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
84
+ REPLACE_UNICODE_PUNCTUATION = [
85
+ (",", ","),
86
+ (r"。\s*", ". "),
87
+ ("、", ","),
88
+ ("”", '"'),
89
+ ("“", '"'),
90
+ ("∶", ":"),
91
+ (":", ":"),
92
+ ("?", "?"),
93
+ ("《", '"'),
94
+ ("》", '"'),
95
+ (")", ")"),
96
+ ("!", "!"),
97
+ ("(", "("),
98
+ (";", ";"),
99
+ ("」", '"'),
100
+ ("「", '"'),
101
+ ("0", "0"),
102
+ ("1", "1"),
103
+ ("2", "2"),
104
+ ("3", "3"),
105
+ ("4", "4"),
106
+ ("5", "5"),
107
+ ("6", "6"),
108
+ ("7", "7"),
109
+ ("8", "8"),
110
+ ("9", "9"),
111
+ (r".\s*", ". "),
112
+ ("~", "~"),
113
+ ("’", "'"),
114
+ ("…", "..."),
115
+ ("━", "-"),
116
+ ("〈", "<"),
117
+ ("〉", ">"),
118
+ ("【", "["),
119
+ ("】", "]"),
120
+ ("%", "%"),
121
+ ]
122
+
123
+ def __init__(
124
+ self,
125
+ lang="en",
126
+ penn=True,
127
+ norm_quote_commas=True,
128
+ norm_numbers=True,
129
+ pre_replace_unicode_punct=False,
130
+ post_remove_control_chars=False,
131
+ ):
132
+ """
133
+ :param language: The two-letter language code.
134
+ :type lang: str
135
+ :param penn: Normalize Penn Treebank style quotations.
136
+ :type penn: bool
137
+ :param norm_quote_commas: Normalize quotations and commas
138
+ :type norm_quote_commas: bool
139
+ :param norm_numbers: Normalize numbers
140
+ :type norm_numbers: bool
141
+ """
142
+ self.substitutions = [
143
+ self.EXTRA_WHITESPACE,
144
+ self.NORMALIZE_UNICODE,
145
+ self.FRENCH_QUOTES,
146
+ self.HANDLE_PSEUDO_SPACES,
147
+ ]
148
+
149
+ if penn: # Adds the penn substitutions after extra_whitespace regexes.
150
+ self.substitutions.insert(1, self.NORMALIZE_UNICODE_IF_NOT_PENN)
151
+
152
+ if norm_quote_commas:
153
+ if lang == "en":
154
+ self.substitutions.append(self.EN_QUOTATION_FOLLOWED_BY_COMMA)
155
+ elif lang in ["de", "es", "fr"]:
156
+ self.substitutions.append(self.DE_ES_FR_QUOTATION_FOLLOWED_BY_COMMA)
157
+
158
+ if norm_numbers:
159
+ if lang in ["de", "es", "cz", "cs", "fr"]:
160
+ self.substitutions.append(self.DE_ES_CZ_CS_FR)
161
+ else:
162
+ self.substitutions.append(self.OTHER)
163
+
164
+ self.substitutions = list(chain(*self.substitutions))
165
+
166
+ self.pre_replace_unicode_punct = pre_replace_unicode_punct
167
+ self.post_remove_control_chars = post_remove_control_chars
168
+
169
+ def normalize(self, text):
170
+ """
171
+ Returns a string with normalized punctuation.
172
+ """
173
+ # Optionally, replace unicode puncts BEFORE normalization.
174
+ if self.pre_replace_unicode_punct:
175
+ text = self.replace_unicode_punct(text)
176
+
177
+ # Actual normalization.
178
+ for regexp, substitution in self.substitutions:
179
+ # print(regexp, substitution)
180
+ text = re.sub(regexp, substitution, str(text))
181
+ # print(text)
182
+
183
+ # Optionally, replace unicode puncts BEFORE normalization.
184
+ if self.post_remove_control_chars:
185
+ text = self.remove_control_chars(text)
186
+
187
+ return text.strip()
188
+
189
+ def replace_unicode_punct(self, text):
190
+ for regexp, substitution in self.REPLACE_UNICODE_PUNCTUATION:
191
+ text = re.sub(regexp, substitution, str(text))
192
+ return text
193
+
194
+ def remove_control_chars(self, text):
195
+ return regex.sub(r"\p{C}", "", text)
196
+
197
+ def _tokenization_norm(text):
198
+ text = text.replace(
199
+ ' ,', ',').replace(
200
+ ' .', '.').replace(
201
+ ' ?', '?').replace(
202
+ ' !', '!').replace(
203
+ ' ;', ';').replace(
204
+ ' \'', '\'').replace(
205
+ ' ’ ', '\'').replace(
206
+ ' :', ':').replace(
207
+ '<newline>', '\n').replace(
208
+ '`` ', '"').replace(
209
+ ' \'\'', '"').replace(
210
+ '\'\'', '"').replace(
211
+ '.. ', '... ').replace(
212
+ ' )', ')').replace(
213
+ '( ', '(').replace(
214
+ ' n\'t', 'n\'t').replace(
215
+ ' i ', ' I ').replace(
216
+ ' i\'', ' I\'').replace(
217
+ '\\\'', '\'').replace(
218
+ '\n ', '\n').strip()
219
+ return text
220
+
221
+
222
+ def _clean_text(text):
223
+ # remove PLM special tokens
224
+ plm_special_tokens = r'(\<pad\>)|(\<s\>)|(\<\/s\>)|(\<unk\>)|(\<\|endoftext\|\>)'
225
+ text = re.sub(plm_special_tokens, "", text)
226
+
227
+ # normalize puncuations
228
+ moses_norm = MosesPunctNormalizer()
229
+ text = moses_norm.normalize(text)
230
+
231
+ # normalize tokenization
232
+ text = _tokenization_norm(text)
233
+
234
+ # remove specific text patterns, e.g,, url, email and phone number
235
+ text = clean(text,
236
+ fix_unicode=True, # fix various unicode errors
237
+ to_ascii=True, # transliterate to closest ASCII representation
238
+ lower=False, # lowercase text
239
+ no_line_breaks=True, # fully strip line breaks as opposed to only normalizing them
240
+ no_urls=True, # replace all URLs with a special token
241
+ no_emails=True, # replace all email addresses with a special token
242
+ no_phone_numbers=True, # replace all phone numbers with a special token
243
+ no_numbers=False, # replace all numbers with a special token
244
+ no_digits=False, # replace all digits with a special token
245
+ no_currency_symbols=False, # replace all currency symbols with a special token
246
+ no_punct=False, # remove punctuations
247
+ replace_with_punct="", # instead of removing punctuations you may replace them
248
+ replace_with_url="",
249
+ replace_with_email="",
250
+ replace_with_phone_number="",
251
+ replace_with_number="<NUMBER>",
252
+ replace_with_digit="<DIGIT>",
253
+ replace_with_currency_symbol="<CUR>",
254
+ lang="en" # set to 'de' for German special handling
255
+ )
256
+
257
+ # keep common puncts only
258
+ punct_pattern = r'[^ A-Za-z0-9.?!,:;\-\[\]\{\}\(\)\'\"]'
259
+ text = re.sub(punct_pattern, '', text)
260
+ # remove specific patterns
261
+ spe_pattern = r'[-\[\]\{\}\(\)\'\"]{2,}'
262
+ text = re.sub(spe_pattern, '', text)
263
+ # remove redundate spaces
264
+ text = " ".join(text.split())
265
+ return text
266
+
267
+ def _rm_line_break(text):
268
+ text = text.replace("\n","\\n")
269
+ text = re.sub(r'(?:\\n)*\\n', r'\\n', text)
270
+ text = re.sub(r'^.{0,3}\\n', '', text)
271
+ text = text.replace("\\n"," ")
272
+ return text
273
+
274
+ def preprocess(text):
275
+ text = _rm_line_break(text)
276
+ text = _clean_text(text)
277
+ return text
278
+
279
+
280
+ def detect(input_text,tokenizer,model,device='cuda:0',th=-3.08583984375):
281
+ label2decisions = {
282
+ 0: "machine-generated",
283
+ 1: "human-written",
284
+ }
285
+ tokenize_input = tokenizer(input_text)
286
+ tensor_input = torch.tensor([tokenize_input["input_ids"]]).to(device)
287
+ outputs = model(tensor_input)
288
+ is_machine = -outputs.logits[0][0].item()
289
+ if is_machine < th:
290
+ decision = 0
291
+ else:
292
+ decision = 1
293
+
294
+ return label2decisions[decision]
src/texts/MAGE/main.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForSequenceClassification,AutoTokenizer
2
+ import datasets
3
+ from deployment import preprocess, detect
4
+ import csv
5
+ import pandas as pd
6
+
7
+ # init
8
+ device = 'cpu' # use 'cuda:0' if GPU is available
9
+ # model_dir = "nealcly/detection-longformer" # model in our paper
10
+ model_dir = "yaful/MAGE" # model in the online demo
11
+ tokenizer = AutoTokenizer.from_pretrained(model_dir)
12
+ model = AutoModelForSequenceClassification.from_pretrained(model_dir).to(device)
13
+
14
+ # text = "Apple's new credit card will begin a preview roll out today and will become available to all iPhone owners in the US later this month. A random selection of people will be allowed to go through the application process, which involves entering personal details which are sent to Goldman Sachs and TransUnion. Applications are approved or declined in less than a minute. The Apple Card is meant to be broadly accessible to every iPhone user, so the approval requirements will not be as strict as other credit cards. Once the application has been approved, users will be able to use the card immediately from the Apple Wallet app. The physical titanium card can be requested during setup for free, and it can be activated with NFC once it arrives."
15
+ # # preprocess
16
+ # text = preprocess(text)
17
+ # # detection
18
+ # result = detect(text,tokenizer,model,device)
19
+ # print(result)
20
+
21
+ # ds = datasets.load_dataset('RealTimeData/bbc_news_alltime', '2020-02')
22
+ # test 100 samples from (RealTimeData/bbc_news_alltime', '2020-02')
23
+ # df = pd.read_csv('query_result.csv')
24
+ # content_column = df['content']
25
+ # count = 0
26
+
27
+ # for content in content_column:
28
+ # # preprocess
29
+ # text = preprocess(content)
30
+ # # detection
31
+ # result = detect(text, tokenizer, model, device)
32
+ # if result == "human-written":
33
+ # count +=1
34
+
35
+ # print(count)
36
+ # print(count)
37
+
38
+
39
+ # ds = datasets.load_dataset('yaful/MAGE', 'test')
40
+ # ds.save_to_disk("MAGE_data")
41
+ # splits = list(ds.keys())
42
+ # print(splits)
43
+
44
+ ds = datasets.load_from_disk("MAGE_data")
45
+
46
+ #filtered_data = ds['test'].filter(lambda x: x['src'] == 'xsum_human')
47
+
48
+ human_data = [example['text'] for example in ds['test'] if example['src'] == 'xsum_human']
49
+ human_data = human_data[0:100]
50
+
51
+ machine_data = [example['text'] for example in ds['test'] if example['src'] == 'xsum_machine_topical_gpt-3.5-trubo']
52
+ machine_data = machine_data[0:100]
53
+
54
+ count = 0
55
+ for content in machine_data:
56
+ # preprocess
57
+ text = preprocess(content)
58
+ # detection
59
+ result = detect(text, tokenizer, model, device)
60
+ print(result)
61
+ if result == "human-written": # machine-generated
62
+ count +=1
63
+
64
+ print(count)
65
+ print(count)
src/texts/MAGE/requirements.txt ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.24.1
2
+ aiohttp==3.9.1
3
+ aiosignal==1.3.1
4
+ async-timeout==4.0.3
5
+ attrs==23.1.0
6
+ certifi==2023.11.17
7
+ charset-normalizer==3.3.2
8
+ clean-text==0.6.0
9
+ click==8.1.7
10
+ datasets==2.15.0
11
+ dill==0.3.7
12
+ emoji==1.7.0
13
+ filelock==3.13.1
14
+ frozenlist==1.4.0
15
+ fsspec==2023.10.0
16
+ ftfy==6.1.3
17
+ huggingface-hub==0.19.4
18
+ idna==3.6
19
+ joblib==1.3.2
20
+ multidict==6.0.4
21
+ multiprocess==0.70.15
22
+ nltk==3.8.1
23
+ numpy==1.26.2
24
+ packaging==23.2
25
+ pandas==2.1.3
26
+ Pillow==10.1.0
27
+ pip==23.3.1
28
+ psutil==5.9.6
29
+ pyarrow==14.0.1
30
+ pyarrow-hotfix==0.6
31
+ python-dateutil==2.8.2
32
+ pytz==2023.3.post1
33
+ PyYAML==6.0.1
34
+ regex==2023.10.3
35
+ requests==2.31.0
36
+ safetensors==0.4.1
37
+ setuptools==68.0.0
38
+ six==1.16.0
39
+ tokenizers==0.15.0
40
+ #torch==1.13.1+cu116
41
+ #torchaudio==0.13.1+cu116
42
+ #torchvision==0.14.1+cu116
43
+ tqdm==4.66.1
44
+ transformers==4.35.2
45
+ typing_extensions==4.8.0
46
+ tzdata==2023.3
47
+ urllib3==2.1.0
48
+ wcwidth==0.2.12
49
+ wheel==0.41.2
50
+ xxhash==3.4.1
51
+ yarl==1.9.3
src/texts/MAGE/training/longformer/main.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2020 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Finetuning the library models for sequence classification on GLUE."""
17
+ # You can also adapt this script on your own text classification task. Pointers for this are left as comments.
18
+
19
+ import logging
20
+ import os
21
+ import random
22
+ import sys
23
+ from dataclasses import dataclass, field
24
+ from typing import Optional
25
+
26
+ import datasets
27
+ import numpy as np
28
+ from datasets import load_dataset, load_metric
29
+
30
+ import transformers
31
+ from transformers import (
32
+ AutoConfig,
33
+ AutoModelForSequenceClassification,
34
+ AutoTokenizer,
35
+ DataCollatorWithPadding,
36
+ EvalPrediction,
37
+ HfArgumentParser,
38
+ PretrainedConfig,
39
+ Trainer,
40
+ TrainingArguments,
41
+ default_data_collator,
42
+ set_seed,
43
+ )
44
+ from transformers.trainer_utils import get_last_checkpoint
45
+ from transformers.utils import check_min_version
46
+ from transformers.utils.versions import require_version
47
+
48
+
49
+ os.environ['CURL_CA_BUNDLE'] = ''
50
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
51
+ check_min_version("4.9.0")
52
+
53
+ require_version("datasets>=1.8.0",
54
+ "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
55
+
56
+ task_to_keys = {
57
+ "cola": ("sentence", None),
58
+ "mnli": ("premise", "hypothesis"),
59
+ "mrpc": ("sentence1", "sentence2"),
60
+ "qnli": ("question", "sentence"),
61
+ "qqp": ("question1", "question2"),
62
+ "rte": ("sentence1", "sentence2"),
63
+ "sst2": ("sentence", None),
64
+ "stsb": ("sentence1", "sentence2"),
65
+ "wnli": ("sentence1", "sentence2"),
66
+ }
67
+
68
+ logger = logging.getLogger(__name__)
69
+
70
+
71
+ @dataclass
72
+ class DataTrainingArguments:
73
+ """
74
+ Arguments pertaining to what data we are going to input our model for training and eval.
75
+ Using `HfArgumentParser` we can turn this class
76
+ into argparse arguments to be able to specify them on
77
+ the command line.
78
+ """
79
+
80
+ task_name: Optional[str] = field(
81
+ default=None,
82
+ metadata={"help": "The name of the task to train on: " +
83
+ ", ".join(task_to_keys.keys())},
84
+ )
85
+ dataset_name: Optional[str] = field(
86
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
87
+ )
88
+ dataset_config_name: Optional[str] = field(
89
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
90
+ )
91
+ max_seq_length: int = field(
92
+ default=128,
93
+ metadata={
94
+ "help": "The maximum total input sequence length after tokenization. Sequences longer "
95
+ "than this will be truncated, sequences shorter will be padded."
96
+ },
97
+ )
98
+ overwrite_cache: bool = field(
99
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
100
+ )
101
+ pad_to_max_length: bool = field(
102
+ default=True,
103
+ metadata={
104
+ "help": "Whether to pad all samples to `max_seq_length`. "
105
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
106
+ },
107
+ )
108
+ max_train_samples: Optional[int] = field(
109
+ default=None,
110
+ metadata={
111
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
112
+ "value if set."
113
+ },
114
+ )
115
+ max_eval_samples: Optional[int] = field(
116
+ default=None,
117
+ metadata={
118
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
119
+ "value if set."
120
+ },
121
+ )
122
+ max_predict_samples: Optional[int] = field(
123
+ default=None,
124
+ metadata={
125
+ "help": "For debugging purposes or quicker training, truncate the number of prediction examples to this "
126
+ "value if set."
127
+ },
128
+ )
129
+ train_file: Optional[str] = field(
130
+ default=None, metadata={"help": "A csv or a json file containing the training data."}
131
+ )
132
+ validation_file: Optional[str] = field(
133
+ default=None, metadata={"help": "A csv or a json file containing the validation data."}
134
+ )
135
+ test_file: Optional[str] = field(default=None, metadata={
136
+ "help": "A csv or a json file containing the test data."})
137
+ from_scratch: bool = field(
138
+ default=False,
139
+ metadata={
140
+ "help": "set true to not load weights from pretrained models."
141
+ },
142
+ )
143
+ # do_eval: Optional[bool] = field(
144
+ # default=False, metadata={"help": "do evaluation."}
145
+ # )
146
+
147
+ def __post_init__(self):
148
+ if self.task_name is not None:
149
+ self.task_name = self.task_name.lower()
150
+ if self.task_name not in task_to_keys.keys():
151
+ raise ValueError(
152
+ "Unknown task, you should pick one in " + ",".join(task_to_keys.keys()))
153
+ elif self.dataset_name is not None:
154
+ pass
155
+ elif self.train_file is None or self.validation_file is None:
156
+ raise ValueError(
157
+ "Need either a GLUE task, a training/validation file or a dataset name.")
158
+ else:
159
+ train_extension = self.train_file.split(".")[-1]
160
+ assert train_extension in [
161
+ "csv", "json"], "`train_file` should be a csv or a json file."
162
+ validation_extension = self.validation_file.split(".")[-1]
163
+ assert (
164
+ validation_extension == train_extension
165
+ ), "`validation_file` should have the same extension (csv or json) as `train_file`."
166
+
167
+
168
+ @dataclass
169
+ class ModelArguments:
170
+ """
171
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
172
+ """
173
+
174
+ model_name_or_path: str = field(
175
+ metadata={
176
+ "help": "Path to pretrained model or model identifier from huggingface.co/models"}
177
+ )
178
+ config_name: Optional[str] = field(
179
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
180
+ )
181
+ tokenizer_name: Optional[str] = field(
182
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
183
+ )
184
+ cache_dir: Optional[str] = field(
185
+ default=None,
186
+ metadata={
187
+ "help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
188
+ )
189
+ use_fast_tokenizer: bool = field(
190
+ default=True,
191
+ metadata={
192
+ "help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
193
+ )
194
+ model_revision: str = field(
195
+ default="main",
196
+ metadata={
197
+ "help": "The specific model version to use (can be a branch name, tag name or commit id)."},
198
+ )
199
+ use_auth_token: bool = field(
200
+ default=False,
201
+ metadata={
202
+ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
203
+ "with private models)."
204
+ },
205
+ )
206
+
207
+
208
+ def main():
209
+ # See all possible arguments in src/transformers/training_args.py
210
+ # or by passing the --help flag to this script.
211
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
212
+
213
+ parser = HfArgumentParser(
214
+ (ModelArguments, DataTrainingArguments, TrainingArguments))
215
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
216
+ # If we pass only one argument to the script and it's the path to a json file,
217
+ # let's parse it to get our arguments.
218
+ model_args, data_args, training_args = parser.parse_json_file(
219
+ json_file=os.path.abspath(sys.argv[1]))
220
+ else:
221
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
222
+
223
+ if data_args.validation_file == data_args.test_file:
224
+ training_args.do_eval = False
225
+
226
+ # Setup logging
227
+ logging.basicConfig(
228
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
229
+ datefmt="%m/%d/%Y %H:%M:%S",
230
+ handlers=[logging.StreamHandler(sys.stdout)],
231
+ )
232
+
233
+ log_level = training_args.get_process_log_level()
234
+ # training_args["report_to"] = None # disable integrations
235
+ logger.setLevel(log_level)
236
+ datasets.utils.logging.set_verbosity(log_level)
237
+ transformers.utils.logging.set_verbosity(log_level)
238
+ transformers.utils.logging.enable_default_handler()
239
+ transformers.utils.logging.enable_explicit_format()
240
+
241
+ # Log on each process the small summary:
242
+ logger.warning(
243
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
244
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
245
+ )
246
+ logger.info(f"Training/evaluation parameters {training_args}")
247
+
248
+ # Detecting last checkpoint.
249
+ last_checkpoint = None
250
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
251
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
252
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
253
+ raise ValueError(
254
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
255
+ "Use --overwrite_output_dir to overcome."
256
+ )
257
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
258
+ logger.info(
259
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
260
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
261
+ )
262
+
263
+ # Set seed before initializing model.
264
+ set_seed(training_args.seed)
265
+
266
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
267
+ # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
268
+ #
269
+ # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the
270
+ # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named
271
+ # label if at least two columns are provided.
272
+ #
273
+ # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
274
+ # single column. You can easily tweak this behavior (see below)
275
+ #
276
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
277
+ # download the dataset.
278
+ if data_args.task_name is not None:
279
+ # Downloading and loading a dataset from the hub.
280
+ raw_datasets = load_dataset(
281
+ "glue", data_args.task_name, cache_dir=model_args.cache_dir)
282
+ elif data_args.dataset_name is not None:
283
+ # Downloading and loading a dataset from the hub.
284
+ raw_datasets = load_dataset(
285
+ data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir
286
+ )
287
+ else:
288
+ # Loading a dataset from your local files.
289
+ # CSV/JSON training and evaluation files are needed.
290
+ data_files = {"train": data_args.train_file,
291
+ "validation": data_args.validation_file}
292
+
293
+ # Get the test dataset: you can provide your own CSV/JSON test file (see below)
294
+ # when you use `do_predict` without specifying a GLUE benchmark task.
295
+ if training_args.do_predict:
296
+ if data_args.test_file is not None:
297
+ train_extension = data_args.train_file.split(".")[-1]
298
+ test_extension = data_args.test_file.split(".")[-1]
299
+ assert (
300
+ test_extension == train_extension
301
+ ), "`test_file` should have the same extension (csv or json) as `train_file`."
302
+ data_files["test"] = data_args.test_file
303
+
304
+ else:
305
+ raise ValueError(
306
+ "Need either a GLUE task or a test file for `do_predict`.")
307
+
308
+ for key in data_files.keys():
309
+ logger.info(f"load a local file for {key}: {data_files[key]}")
310
+
311
+ if data_args.train_file.endswith(".csv"):
312
+ # Loading a dataset from local csv files
313
+ raw_datasets = load_dataset(
314
+ "csv", data_files=data_files, cache_dir=model_args.cache_dir)
315
+ else:
316
+ # Loading a dataset from local json files
317
+ raw_datasets = load_dataset(
318
+ "json", data_files=data_files, cache_dir=model_args.cache_dir)
319
+ # See more about loading any type of standard or custom dataset at
320
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
321
+
322
+ # Labels
323
+ if data_args.task_name is not None:
324
+ is_regression = data_args.task_name == "stsb"
325
+ if not is_regression:
326
+ label_list = raw_datasets["train"].features["label"].names
327
+ num_labels = len(label_list)
328
+ else:
329
+ num_labels = 1
330
+ else:
331
+ # Trying to have good defaults here, don't hesitate to tweak to your needs.
332
+ is_regression = raw_datasets["train"].features["label"].dtype in [
333
+ "float32", "float64"]
334
+ if is_regression:
335
+ num_labels = 1
336
+ else:
337
+ # A useful fast method:
338
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique
339
+ label_list = raw_datasets["train"].unique("label")
340
+ label_list.sort() # Let's sort it for determinism
341
+ num_labels = len(label_list)
342
+
343
+ # Load pretrained model and tokenizer
344
+ #
345
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
346
+ # download model & vocab.
347
+ config = AutoConfig.from_pretrained(
348
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
349
+ num_labels=num_labels,
350
+ finetuning_task=data_args.task_name,
351
+ cache_dir=model_args.cache_dir,
352
+ revision=model_args.model_revision,
353
+ use_auth_token=True if model_args.use_auth_token else None,
354
+ )
355
+ tokenizer = AutoTokenizer.from_pretrained(
356
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
357
+ cache_dir=model_args.cache_dir,
358
+ use_fast=model_args.use_fast_tokenizer,
359
+ revision=model_args.model_revision,
360
+ use_auth_token=True if model_args.use_auth_token else None,
361
+ )
362
+ if not data_args.from_scratch:
363
+ model = AutoModelForSequenceClassification.from_pretrained(
364
+ model_args.model_name_or_path,
365
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
366
+ config=config,
367
+ cache_dir=model_args.cache_dir,
368
+ revision=model_args.model_revision,
369
+ use_auth_token=True if model_args.use_auth_token else None,
370
+ ignore_mismatched_sizes=True,
371
+ )
372
+ else:
373
+ model = AutoModelForSequenceClassification.from_config(
374
+ config=config,
375
+ # ignore_mismatched_sizes=True,
376
+ )
377
+ # Preprocessing the raw_datasets
378
+ sentence1_key, sentence2_key = "text", None
379
+ # if data_args.task_name is not None:
380
+ # sentence1_key, sentence2_key = task_to_keys[data_args.task_name]
381
+ # else:
382
+ # # Again, we try to have some nice defaults but don't hesitate to tweak to your use case.
383
+ # non_label_column_names = [name for name in raw_datasets["train"].column_names if name != "label"]
384
+ # if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
385
+ # sentence1_key, sentence2_key = "sentence1", "sentence2"
386
+ # else:
387
+ # if len(non_label_column_names) >= 2:
388
+ # sentence1_key, sentence2_key = non_label_column_names[:2]
389
+ # else:
390
+ # sentence1_key, sentence2_key = non_label_column_names[0], None
391
+
392
+ # Padding strategy
393
+ if data_args.pad_to_max_length:
394
+ padding = "max_length"
395
+ else:
396
+ # We will pad later, dynamically at batch creation, to the max sequence length in each batch
397
+ padding = False
398
+
399
+ # Some models have set the order of the labels to use, so let's make sure we do use it.
400
+ label_to_id = None
401
+ if (
402
+ model.config.label2id != PretrainedConfig(
403
+ num_labels=num_labels).label2id
404
+ and data_args.task_name is not None
405
+ and not is_regression
406
+ ):
407
+ # Some have all caps in their config, some don't.
408
+ label_name_to_id = {
409
+ k.lower(): v for k, v in model.config.label2id.items()}
410
+ if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)):
411
+ label_to_id = {
412
+ i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)}
413
+ else:
414
+ logger.warning(
415
+ "Your model seems to have been trained with labels, but they don't match the dataset: ",
416
+ f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}."
417
+ "\nIgnoring the model labels as a result.",
418
+ )
419
+ elif data_args.task_name is None and not is_regression:
420
+ label_to_id = {v: i for i, v in enumerate(label_list)}
421
+
422
+ if label_to_id is not None:
423
+ model.config.label2id = label_to_id
424
+ model.config.id2label = {
425
+ id: label for label, id in config.label2id.items()}
426
+
427
+ if data_args.max_seq_length > tokenizer.model_max_length:
428
+ logger.warning(
429
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
430
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
431
+ )
432
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
433
+
434
+ def preprocess_function(examples):
435
+ # Tokenize the texts
436
+ args = (
437
+ (examples[sentence1_key],) if sentence2_key is None else (
438
+ examples[sentence1_key], examples[sentence2_key])
439
+ )
440
+ result = tokenizer(*args, padding=padding,
441
+ max_length=max_seq_length, truncation=True)
442
+ # print('finish')
443
+ # print(examples[sentence1_key])
444
+ # Map labels to IDs (not necessary for GLUE tasks)
445
+
446
+ result["label"] = examples['label']
447
+ return result
448
+
449
+ with training_args.main_process_first(desc="dataset map pre-processing"):
450
+ raw_datasets = raw_datasets.map(
451
+ preprocess_function,
452
+ batched=True,
453
+ load_from_cache_file=not data_args.overwrite_cache,
454
+ desc="Running tokenizer on dataset",
455
+ )
456
+ if training_args.do_train:
457
+ if "train" not in raw_datasets:
458
+ raise ValueError("--do_train requires a train dataset")
459
+ train_dataset = raw_datasets["train"]
460
+ if data_args.max_train_samples is not None:
461
+ train_dataset = train_dataset.select(
462
+ range(data_args.max_train_samples))
463
+ # print(training_args.do_eval)
464
+ # xxx
465
+ if training_args.do_eval:
466
+ if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
467
+ raise ValueError("--do_eval requires a validation dataset")
468
+ eval_dataset = raw_datasets["validation_matched" if data_args.task_name ==
469
+ "mnli" else "validation"]
470
+ if data_args.max_eval_samples is not None:
471
+ eval_dataset = eval_dataset.select(
472
+ range(data_args.max_eval_samples))
473
+
474
+ if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None:
475
+ if "test" not in raw_datasets and "test_matched" not in raw_datasets:
476
+ raise ValueError("--do_predict requires a test dataset")
477
+ predict_dataset = raw_datasets["test_matched" if data_args.task_name ==
478
+ "mnli" else "test"]
479
+ if data_args.max_predict_samples is not None:
480
+ predict_dataset = predict_dataset.select(
481
+ range(data_args.max_predict_samples))
482
+
483
+ # Log a few random samples from the training set:
484
+ if training_args.do_train:
485
+ for index in random.sample(range(len(train_dataset)), 3):
486
+ logger.info(
487
+ f"Sample {index} of the training set: {train_dataset[index]}.")
488
+
489
+ # Get the metric function
490
+ # if data_args.task_name is not None:
491
+ # metric = load_metric("glue", data_args.task_name)
492
+ # else:
493
+ # metric = load_metric("accuracy", cache_dir='./evaluate')
494
+
495
+ # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
496
+ # predictions and label_ids field) and has to return a dictionary string to float.
497
+ def compute_metrics(p: EvalPrediction):
498
+ preds = p.predictions[0] if isinstance(
499
+ p.predictions, tuple) else p.predictions
500
+ preds = np.squeeze(
501
+ preds) if is_regression else np.argmax(preds, axis=1)
502
+ # if data_args.task_name is not None:
503
+ # result = metric.compute(predictions=preds, references=p.label_ids)
504
+ # if len(result) > 1:
505
+ # result["combined_score"] = np.mean(list(result.values())).item()
506
+ # return result
507
+ if is_regression:
508
+ return {"mse": ((preds - p.label_ids) ** 2).mean().item()}
509
+ else:
510
+ accuracy = (preds == p.label_ids).astype(np.float32).mean().item()
511
+ TP = ((preds == p.label_ids) & (preds == 1)
512
+ ).astype(np.float32).sum().item()
513
+ TN = ((preds == p.label_ids) & (preds == 0)
514
+ ).astype(np.float32).sum().item()
515
+ FN = ((preds != p.label_ids) & (preds == 0)
516
+ ).astype(np.float32).sum().item()
517
+ FP = ((preds != p.label_ids) & (preds == 1)
518
+ ).astype(np.float32).sum().item()
519
+
520
+ # metric_precision = load_metric("precision", cache_dir='./evaluate')
521
+ # precision = metric_precision.compute(predictions=preds, references=p.label_ids, average='macro')
522
+ # metric_recall = load_metric("recall", cache_dir='./evaluate')
523
+ # recall = metric_recall.compute(predictions=preds, references=p.label_ids, average='macro')
524
+ # metric_fscore = load_metric("f1", cache_dir='./evaluate')
525
+ # f1score = metric_fscore.compute(predictions=preds, references=p.label_ids, average='macro')
526
+ # print("-"*100)
527
+ try:
528
+ precision = TP / (TP+FP)
529
+ recall = TP / (TP+FN)
530
+ f1score = 2*precision*recall/(precision+recall)
531
+ print(f'precision:{precision}/recall"{recall}/f1:{f1score}')
532
+ precision = TN / (TN+FN)
533
+ recall = TN / (TN+FP)
534
+ f1score = 2*precision*recall/(precision+recall)
535
+ print(f'precision:{precision}/recall"{recall}/f1:{f1score}')
536
+ except:
537
+ print("float division by zero ...")
538
+ # return {
539
+ # "precision": precision,
540
+ # "recall": recall,
541
+ # "f1": f1score
542
+ # }
543
+ return {
544
+ "accuracy": accuracy
545
+ }
546
+ # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
547
+ if data_args.pad_to_max_length:
548
+ data_collator = default_data_collator
549
+ elif training_args.fp16:
550
+ data_collator = DataCollatorWithPadding(
551
+ tokenizer, pad_to_multiple_of=8)
552
+ else:
553
+ data_collator = None
554
+
555
+ # Initialize our Trainer
556
+ trainer = Trainer(
557
+ model=model,
558
+ args=training_args,
559
+ train_dataset=train_dataset if training_args.do_train else None,
560
+ eval_dataset=eval_dataset if training_args.do_eval else None,
561
+ compute_metrics=compute_metrics,
562
+ tokenizer=tokenizer,
563
+ data_collator=data_collator,
564
+ )
565
+
566
+ # Training
567
+ if training_args.do_train:
568
+ checkpoint = None
569
+ if training_args.resume_from_checkpoint is not None:
570
+ checkpoint = training_args.resume_from_checkpoint
571
+ elif last_checkpoint is not None:
572
+ checkpoint = last_checkpoint
573
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
574
+ metrics = train_result.metrics
575
+ max_train_samples = (
576
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(
577
+ train_dataset)
578
+ )
579
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
580
+
581
+ trainer.save_model() # Saves the tokenizer too for easy upload
582
+
583
+ trainer.log_metrics("train", metrics)
584
+ trainer.save_metrics("train", metrics)
585
+ trainer.save_state()
586
+
587
+ # Evaluation
588
+ if training_args.do_eval:
589
+ logger.info("*** Evaluate ***")
590
+
591
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
592
+ tasks = [data_args.task_name]
593
+ eval_datasets = [eval_dataset]
594
+ if data_args.task_name == "mnli":
595
+ tasks.append("mnli-mm")
596
+ eval_datasets.append(raw_datasets["validation_mismatched"])
597
+
598
+ for eval_dataset, task in zip(eval_datasets, tasks):
599
+ metrics = trainer.evaluate(eval_dataset=eval_dataset)
600
+
601
+ max_eval_samples = (
602
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(
603
+ eval_dataset)
604
+ )
605
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
606
+
607
+ trainer.log_metrics("eval", metrics)
608
+ trainer.save_metrics("eval", metrics)
609
+
610
+ if training_args.do_predict:
611
+ logger.info("*** Predict ***")
612
+
613
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
614
+ tasks = [data_args.task_name]
615
+ predict_datasets = [predict_dataset]
616
+ if data_args.task_name == "mnli":
617
+ tasks.append("mnli-mm")
618
+ predict_datasets.append(raw_datasets["test_mismatched"])
619
+
620
+ for predict_dataset, task in zip(predict_datasets, tasks):
621
+ # Removing the `label` columns because it contains -1 and Trainer won't like that.
622
+ predict_dataset = predict_dataset.remove_columns("label")
623
+ predictions = trainer.predict(
624
+ predict_dataset, metric_key_prefix="predict").predictions
625
+
626
+ # save probability
627
+ out_predprob_file = os.path.join(
628
+ training_args.output_dir, f"predict_results_probs.csv")
629
+ np.savetxt(out_predprob_file, predictions, delimiter=",")
630
+
631
+ # save predictions
632
+ predictions = np.squeeze(
633
+ predictions) if is_regression else np.argmax(predictions, axis=1)
634
+
635
+ output_predict_file = os.path.join(
636
+ training_args.output_dir, f"predict_results_{task}.txt")
637
+ if trainer.is_world_process_zero():
638
+ with open(output_predict_file, "w") as writer:
639
+ logger.info(f"***** Predict results {task} *****")
640
+ writer.write("index\tprediction\n")
641
+ for index, item in enumerate(predictions):
642
+ if is_regression:
643
+ writer.write(f"{index}\t{item:3.3f}\n")
644
+ else:
645
+ item = label_list[item]
646
+ writer.write(f"{index}\t{item}\n")
647
+
648
+ if training_args.push_to_hub:
649
+ kwargs = {"finetuned_from": model_args.model_name_or_path,
650
+ "tasks": "text-classification"}
651
+ if data_args.task_name is not None:
652
+ kwargs["language"] = "en"
653
+ kwargs["dataset_tags"] = "glue"
654
+ kwargs["dataset_args"] = data_args.task_name
655
+ kwargs["dataset"] = f"GLUE {data_args.task_name.upper()}"
656
+
657
+ trainer.push_to_hub(**kwargs)
658
+
659
+
660
+ def _mp_fn(index):
661
+ # For xla_spawn (TPUs)
662
+ main()
663
+
664
+
665
+ if __name__ == "__main__":
666
+ main()