SixOpen commited on
Commit
adbf50c
·
1 Parent(s): de196a4
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ Weights filter=lfs diff=lfs merge=lfs -text
37
+ Weights/* filter=lfs diff=lfs merge=lfs -text
.github/.devcontainer.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Python Development Container",
3
+ "image": "mcr.microsoft.com/devcontainers/base:ubuntu",
4
+ "features": {
5
+ "ghcr.io/devcontainers/features/python": {
6
+ "version": "latest"
7
+ }
8
+ },
9
+ "postCreateCommand": "pip install -e ."
10
+ }
.github/ISSUE_TEMPLATE/bug_report.yaml ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F41B Bug Report"
2
+ description: Submit a bug report to help us improve
3
+ title: "[BUG]: "
4
+ projects:
5
+ - "project-name"
6
+ labels:
7
+ - bug
8
+ body:
9
+ - type: markdown
10
+ attributes:
11
+ value: |
12
+ Thanks for taking the time to fill out this bug report!
13
+ Please make sure you have searched for a similar [issue](https://github.com/mozilla-ai/project-name/issues) before submitting a new one.
14
+
15
+ - type: textarea
16
+ id: description
17
+ attributes:
18
+ label: Description
19
+ description: A clear and concise description of what the bug is.
20
+ placeholder: |
21
+ When I try to...
22
+ validations:
23
+ required: true
24
+
25
+ - type: textarea
26
+ id: reproduction
27
+ attributes:
28
+ label: Reproduction
29
+ description: |
30
+ Provide a numbered list of steps that one can follow to reproduce this behavior.
31
+ placeholder: |
32
+ Steps to reproduce the behavior:
33
+ 1.
34
+ 2.
35
+ 3.
36
+ validations:
37
+ required: true
38
+
39
+ - type: textarea
40
+ id: logs
41
+ attributes:
42
+ label: Relevant log output
43
+ description: |
44
+ Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
45
+ render: shell
46
+ validations:
47
+ required: false
48
+
49
+ - type: textarea
50
+ id: expected-behavior
51
+ attributes:
52
+ label: Expected behavior
53
+ description: A clear description of what you would expect to happen.
54
+ placeholder: "I would expect to..."
55
+ validations:
56
+ required: true
57
+
58
+ - type: textarea
59
+ id: system-info
60
+ attributes:
61
+ label: System Info
62
+ description: Please share your system info with us.
63
+ placeholder: |
64
+ - OS: [e.g., macOS Sonoma]
65
+ - Project-name version: [e.g. commit SHA]
66
+ validations:
67
+ required: true
68
+
69
+ - type: checkboxes
70
+ id: search
71
+ attributes:
72
+ label: Have you searched for similar issues before submitting this one?
73
+ options:
74
+ - label: Yes, I have searched for similar issues
75
+ required: true
.github/ISSUE_TEMPLATE/feature_request.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "\U0001F680 Feature Request"
2
+ description: Suggest an idea for this project
3
+ title: "[FEATURE]: "
4
+ projects:
5
+ - "Project-name"
6
+ labels:
7
+ - enhancement
8
+ body:
9
+ - type: markdown
10
+ attributes:
11
+ value: |
12
+ Thanks for taking the time to fill out this form!
13
+ Please make sure you have searched for a similar [issue](https://github.com/mozilla-ai/project-name/issues) before submitting a new one.
14
+
15
+ - type: textarea
16
+ id: motivation
17
+ attributes:
18
+ label: Motivation
19
+ description: |
20
+ A clear and concise description of the proposal and why this is important.
21
+ placeholder: |
22
+ I'm always frustrated when...
23
+ validations:
24
+ required: true
25
+
26
+ - type: textarea
27
+ id: alternatives
28
+ attributes:
29
+ label: Alternatives
30
+ description: |
31
+ A clear and concise description of any alternative solutions or features you've considered.
32
+ placeholder: |
33
+ I've considered...
34
+ validations:
35
+ required: false
36
+
37
+ - type: textarea
38
+ id: contribution
39
+ attributes:
40
+ label: Contribution
41
+ description: |
42
+ Is there any way that you could help, e.g. by submitting a PR?
43
+ Make sure to read the [contribution guidelines](https://github.com/mozilla-ai/project-name/blob/main/CONTRIBUTING.md).
44
+ placeholder: |
45
+ I could help by...
46
+ validations:
47
+ required: false
48
+
49
+ - type: checkboxes
50
+ id: search
51
+ attributes:
52
+ label: Have you searched for similar issues before submitting this one?
53
+ options:
54
+ - label: Yes, I have searched for similar issues
55
+ required: true
.github/pull_request_template.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What's changing
2
+
3
+ Provide a clear and concise description of the content changes you're proposing. List all the
4
+ changes you are making to the content.
5
+
6
+ > If this PR is related to an issue or closes one, please link it here.
7
+
8
+ Refs #...
9
+ Closes #...
10
+
11
+ # How to test it
12
+
13
+ Steps to test the changes:
14
+
15
+ 1.
16
+ 2.
17
+ 3.
18
+
19
+ # Additional notes for reviewers
20
+
21
+ Anything you'd like to add to help the reviewer understand the changes you're proposing.
22
+
23
+ # I already...
24
+
25
+ - [ ] Tested the changes in a working environment to ensure they work as expected
26
+ - [ ] Added some tests for any new functionality
27
+ - [ ] Updated the documentation (both comments in code and under `/docs`)
.github/workflows/docs.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Documentation
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ paths:
7
+ - mkdocs.yml
8
+ - 'docs/**'
9
+ - 'src/**'
10
+ pull_request:
11
+ paths:
12
+ - mkdocs.yml
13
+ - 'docs/**'
14
+ - 'src/**'
15
+ workflow_dispatch:
16
+
17
+ jobs:
18
+ docs:
19
+ permissions:
20
+ contents: write
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - name: Check out the repository
24
+ uses: actions/checkout@v4
25
+ with:
26
+ fetch-depth: 0
27
+
28
+ - name: Set up Python
29
+ uses: actions/setup-python@v5
30
+ with:
31
+ python-version: '3.10'
32
+ cache: "pip"
33
+
34
+ - name: Configure git
35
+ run: |
36
+ git config user.name 'github-actions[bot]'
37
+ git config user.email 'github-actions[bot]@users.noreply.github.com'
38
+
39
+ - name: Install requirements
40
+ run: pip install -e '.[docs]'
41
+
42
+ - name: Build docs
43
+ if: github.event_name == 'pull_request'
44
+ run: mkdocs build -s
45
+
46
+ - name: Publish docs
47
+ if: ${{ github.event_name == 'push' || github.event_name == 'workflow_dispatch' }}
48
+ run: mkdocs gh-deploy
.github/workflows/lint.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Lint
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ run-linter:
11
+ timeout-minutes: 30
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - name: Check out the repository
16
+ uses: actions/checkout@v4
17
+
18
+ - name: Set up Python
19
+ uses: actions/setup-python@v5
20
+ with:
21
+ python-version: '3.10'
22
+
23
+ - name: Install pre-commit
24
+ run: pip install pre-commit
25
+
26
+ - uses: actions/cache@v4
27
+ with:
28
+ path: ~/.cache/pre-commit/
29
+ key: pre-commit-4|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
30
+
31
+ - name: pre-commit
32
+ run: pre-commit run --all-files
.github/workflows/package.yaml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Create and publish a Docker image
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - 'main'
7
+ tags:
8
+ - 'v*'
9
+ workflow_dispatch:
10
+
11
+ jobs:
12
+ build-and-push-image:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Checkout repository
16
+ uses: actions/checkout@v4
17
+
18
+ - name: Log in to DockerHub
19
+ uses: docker/login-action@v3
20
+ with:
21
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
22
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
23
+
24
+ - name: Extract metadata (tags, labels) for Docker
25
+ id: meta
26
+ uses: docker/metadata-action@v5
27
+ with:
28
+ images: mzdotai/blueprint
29
+ flavor: |
30
+ latest=auto
31
+
32
+ - name: Build and push Docker image
33
+ id: push
34
+ uses: docker/build-push-action@v6
35
+ with:
36
+ context: .
37
+ push: true
38
+ tags: ${{ steps.meta.outputs.tags }}
39
+ labels: ${{ steps.meta.outputs.labels }}
.github/workflows/release.yaml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ release:
10
+ environment: pypi
11
+ permissions:
12
+ contents: read
13
+ id-token: write
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - name: Check out the repository
17
+ uses: actions/checkout@v4
18
+ with:
19
+ fetch-depth: 0
20
+
21
+ - name: Set up Python
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: '3.10'
25
+
26
+ - name: Upgrade pip
27
+ run: |
28
+ pip install --upgrade pip
29
+ pip --version
30
+
31
+ - name: Install
32
+ run: python -m pip install build setuptools
33
+
34
+ - name: Build package
35
+ run: python -m build
36
+
37
+ - name: Upload package
38
+ if: github.event_name == 'release'
39
+ uses: pypa/gh-action-pypi-publish@release/v1
.github/workflows/tests.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ paths:
7
+ - 'src/**'
8
+ - 'tests/**'
9
+ pull_request:
10
+ paths:
11
+ - 'src/**'
12
+ - 'tests/**'
13
+ workflow_dispatch:
14
+
15
+ jobs:
16
+ run-tests:
17
+ timeout-minutes: 30
18
+ runs-on: ubuntu-latest
19
+
20
+ steps:
21
+ - name: Check out the repository
22
+ uses: actions/checkout@v4
23
+
24
+ - name: Set up Python
25
+ uses: actions/setup-python@v5
26
+ with:
27
+ python-version: '3.10'
28
+ cache: "pip"
29
+
30
+ - name: Install
31
+ run: pip install -e '.[tests]'
32
+
33
+ - name: Run tests
34
+ run: pytest -v tests
.gitignore ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+
163
+ .idea/
164
+ .vscode/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v5.0.0
4
+ hooks:
5
+ - id: check-added-large-files
6
+ - id: check-case-conflict
7
+ - id: check-json
8
+ - id: check-merge-conflict
9
+ args: ['--assume-in-merge']
10
+ - id: check-toml
11
+ - id: check-yaml
12
+ - id: end-of-file-fixer
13
+ - id: mixed-line-ending
14
+ args: ['--fix=lf']
15
+ - id: sort-simple-yaml
16
+ - id: trailing-whitespace
17
+ - repo: https://github.com/astral-sh/ruff-pre-commit
18
+ rev: 'v0.7.3'
19
+ hooks:
20
+ - id: ruff
21
+ args: [--fix, --exit-non-zero-on-fix]
22
+ - id: ruff-format
23
+ - repo: https://github.com/codespell-project/codespell
24
+ rev: v2.3.0
25
+ hooks:
26
+ - id: codespell
27
+ exclude: CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the team at mozilla.ai. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
+
73
+ [homepage]: https://www.contributor-covenant.org
74
+
75
+ For answers to common questions about this code of conduct, see
76
+ https://www.contributor-covenant.org/faq
CONTRIBUTING.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Contributing to mozilla.ai Blueprints
2
+
3
+ We welcome contributions of all kinds! Whether you're a seasoned developer or just starting out, your help is greatly appreciated.
4
+
5
+ # How to Contribute
6
+
7
+ ---
Dockerfile ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ RUN pip3 install --no-cache-dir --upgrade pip
4
+ RUN apt-get update && apt-get install -y \
5
+ build-essential \
6
+ software-properties-common \
7
+ git \
8
+ ffmpeg \
9
+ libsm6 \
10
+ libxext6 \
11
+ cmake \
12
+ libgl1-mesa-glx
13
+
14
+ RUN pip3 install streamlit
15
+
16
+ RUN groupadd --gid 1000 appuser \
17
+ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser
18
+
19
+ RUN mkdir -p /home/appuser/.cache /home/appuser/.config \
20
+ && chown -R appuser:appuser /home/appuser
21
+
22
+ WORKDIR /home/appuser/blueprint
23
+ COPY --chown=appuser:appuser . .
24
+
25
+ RUN chmod +x demo/run.sh
26
+
27
+ USER appuser
28
+
29
+ ENV PATH="/home/appuser/.local/bin:${PATH}"
30
+ RUN mkdir -p /home/appuser/tmp && chmod 777 /home/appuser/tmp
31
+ ENV TMPDIR=/home/appuser/tmp
32
+
33
+ RUN pip3 install -e .
34
+
35
+ EXPOSE 8501
36
+ ENTRYPOINT ["./demo/run.sh"]
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.
README.md CHANGED
@@ -1,10 +1,55 @@
1
  ---
2
- title: WIPDockerBP
3
- emoji: 🐨
4
- colorFrom: blue
5
- colorTo: indigo
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Wip1docker
3
+ emoji: 👀
4
+ colorFrom: green
5
+ colorTo: purple
6
  sdk: docker
7
+ app_port: 8501
8
  pinned: false
9
  ---
10
 
11
+
12
+
13
+
14
+ <p align="center"><img src="./images/Blueprints-logo.png" width="35%" alt="Project logo"/></p>
15
+
16
+ This blueprint guides you to ...
17
+
18
+ ### 👉 📖 For more detailed guidance on using this project, please visit our [Docs here](https://mozilla-ai.github.io/Blueprint-template/)
19
+
20
+ ### Built with
21
+ - Python 3.10+
22
+ - Open-Source Tool 1
23
+ - Open-Source Tool 2
24
+ - ...
25
+
26
+ ## Quick-start
27
+
28
+
29
+ ## How it Works
30
+
31
+
32
+ ## Pre-requisites
33
+
34
+ - **System requirements**:
35
+ - OS: Windows, macOS, or Linux
36
+ - Python 3.10 or higher
37
+ - Minimum RAM:
38
+ - Disk space:
39
+
40
+ - **Dependencies**:
41
+ - Dependencies listed in `pyproject.toml`
42
+
43
+
44
+ ## Troubleshooting
45
+
46
+
47
+ ## License
48
+
49
+ This project is licensed under the Apache 2.0 License. See the [LICENSE](LICENSE) file for details.
50
+
51
+ ## Contributing
52
+
53
+ Contributions are welcome! To get started, you can check out the [CONTRIBUTING.md](CONTRIBUTING.md) file.
54
+
55
+ ## WIP
Weights/shape_predictor_81_face_landmarks.dat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cae4375589dd915d9a0a881101bed1bbb4e9887e35e63b024388f1ca25ff869
3
+ size 19743860
Weights/weights.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c100e98694faa776fcf71990377f9c4eca46568417339c06843cdcf2a78d35d
3
+ size 141291061
demo/app.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import warnings
3
+ import cv2
4
+ import dlib
5
+ from pytorch_grad_cam.utils.image import show_cam_on_image
6
+ from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
7
+ import numpy as np
8
+ import torch
9
+ from retinaface.pre_trained_models import get_model
10
+ from blueprint.model import create_model, create_cam
11
+ from blueprint.preprocess import crop_face, extract_face, extract_frames
12
+ from pathlib import Path
13
+ import tempfile
14
+ import os
15
+ import io
16
+
17
+ warnings.filterwarnings('ignore')
18
+ ROOT_DIR = Path(__file__).parent.parent
19
+
20
+ def aca(img):
21
+ if len(img.shape) == 3 and img.shape[2] == 3:
22
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
23
+ img_float = img.astype(np.float32) / 255.0
24
+ channels = np.moveaxis(img_float, -1, 0)
25
+ sorted_idx = np.argsort(channels, axis=0)
26
+ sorted_values = np.take_along_axis(channels, sorted_idx, axis=0)
27
+ L = sorted_values[0]
28
+ M = sorted_values[1]
29
+ U = sorted_values[2]
30
+ eps = 1e-10
31
+ L_U = L / (U + eps)
32
+ L_M = L / (M + eps)
33
+ M_U = M / (U + eps)
34
+ kernel = np.array([[1, 0, 1], [0, -4, 0], [1, 0, 1]], dtype=np.float32)
35
+ L_U_filtered = cv2.filter2D(np.log(L_U + eps), -1, kernel)
36
+ L_M_filtered = cv2.filter2D(np.log(L_M + eps), -1, kernel)
37
+ M_U_filtered = cv2.filter2D(np.log(M_U + eps), -1, kernel)
38
+ residuals = np.abs(L_U_filtered) + np.abs(L_M_filtered) + np.abs(M_U_filtered)
39
+ p1, p99 = np.percentile(residuals[residuals > 0], (1, 99))
40
+ normalized = np.clip((residuals - p1) / (p99 - p1), 0, 1)
41
+ significant = normalized > 0.1
42
+ result = np.zeros((*residuals.shape, 3), dtype=np.float32)
43
+ result[significant, 0] = 255
44
+ intensity = np.expand_dims(normalized, -1)
45
+ result = result * intensity
46
+ return result.astype(np.uint8)
47
+
48
+ def perform_ela(img, quality=95, scale=15):
49
+ buffer = io.BytesIO()
50
+ if len(img.shape) == 3 and img.shape[2] == 3:
51
+ working_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
52
+ else:
53
+ working_img = img.copy()
54
+ img_bytes = cv2.imencode('.jpg', working_img, [cv2.IMWRITE_JPEG_QUALITY, quality])[1].tobytes()
55
+ buffer.write(img_bytes)
56
+ buffer.seek(0)
57
+ compressed_img = cv2.imdecode(np.frombuffer(buffer.read(), np.uint8), cv2.IMREAD_COLOR)
58
+ difference = np.abs(working_img.astype(np.float32) - compressed_img.astype(np.float32)) * scale
59
+ difference = np.clip(difference, 0, 255).astype(np.uint8)
60
+ difference_rgb = cv2.cvtColor(difference, cv2.COLOR_BGR2RGB)
61
+ luminance = np.sum(difference_rgb * np.array([0.299, 0.587, 0.114]), axis=2)
62
+ enhanced = np.zeros_like(difference_rgb)
63
+ for i in range(3):
64
+ enhanced[:,:,i] = np.minimum(difference_rgb[:,:,i] * 2, 255)
65
+ mask = luminance < np.mean(luminance) * 0.5
66
+ enhanced[mask] = [0, 0, 0]
67
+ gamma = 1.4
68
+ enhanced = (((enhanced / 255.0) ** (1/gamma)) * 255).astype(np.uint8)
69
+ return difference, enhanced
70
+
71
+ @st.cache_resource
72
+ def load_models():
73
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
74
+ sbcl = create_model(str(ROOT_DIR / "Weights/weights.tar"), device)
75
+ face_detector = get_model("resnet50_2020-07-20", max_size=1024, device=device)
76
+ face_detector.eval()
77
+ cam_sbcl = create_cam(sbcl)
78
+ dlib_face_detector = dlib.get_frontal_face_detector()
79
+ dlib_face_predictor = dlib.shape_predictor(str(ROOT_DIR / "Weights/shape_predictor_81_face_landmarks.dat"))
80
+ return device, sbcl, face_detector, cam_sbcl, dlib_face_detector, dlib_face_predictor
81
+
82
+ def predict_image(inp, models):
83
+ device, sbcl, face_detector, cam_sbcl = models[:4]
84
+ targets = [ClassifierOutputTarget(1)]
85
+ if inp is None:
86
+ return None, None
87
+ face_list = extract_face(inp, face_detector)
88
+ if len(face_list) == 0:
89
+ return None, None
90
+ try:
91
+ img = torch.tensor(face_list).to(device)
92
+ if device.type == 'cuda':
93
+ img = img.half()
94
+ img = img / 255
95
+ with torch.no_grad():
96
+ pred = sbcl(img).float().softmax(1)[:, 1].cpu().numpy().tolist()[0]
97
+ confidences = {'Real': 1 - pred, 'Fake': pred}
98
+ img.requires_grad = True
99
+ grayscale_cam = cam_sbcl(input_tensor=img, targets=targets, aug_smooth=True)
100
+ grayscale_cam = grayscale_cam[0, :]
101
+ cam_image = show_cam_on_image(face_list[0].transpose(1, 2, 0) / 255, grayscale_cam, use_rgb=True)
102
+ return confidences, cam_image
103
+ except Exception as e:
104
+ st.error(f"Error during prediction: {str(e)}")
105
+ return None, None
106
+
107
+ def predict_video(inp, models):
108
+ device, sbcl, face_detector, cam_sbcl = models[:4]
109
+ targets = [ClassifierOutputTarget(1)]
110
+ if inp is None:
111
+ return None, None
112
+ try:
113
+ face_list, idx_list = extract_frames(inp, 10, face_detector)
114
+ if not face_list:
115
+ return None, None
116
+ img = torch.tensor(face_list).to(device)
117
+ if device.type == 'cuda':
118
+ img = img.half()
119
+ img = img / 255
120
+ with torch.no_grad():
121
+ pred = sbcl(img).float().softmax(1)[:, 1]
122
+ pred_list = []
123
+ idx_img = -1
124
+ for i in range(len(pred)):
125
+ if idx_list[i] != idx_img:
126
+ pred_list.append([])
127
+ idx_img = idx_list[i]
128
+ pred_list[-1].append(pred[i].item())
129
+ pred_res = np.array([max(p) for p in pred_list])
130
+ pred = float(pred_res.mean())
131
+ most_fake = np.argmax(pred_res)
132
+ img_for_cam = img[most_fake].unsqueeze(0)
133
+ img_for_cam.requires_grad = True
134
+ grayscale_cam = cam_sbcl(input_tensor=img_for_cam, targets=targets, aug_smooth=True)
135
+ grayscale_cam = grayscale_cam[0, :]
136
+ cam_image = show_cam_on_image(face_list[most_fake].transpose(1, 2, 0) / 255, grayscale_cam, use_rgb=True)
137
+ return {'Real': 1 - pred, 'Fake': pred}, cam_image
138
+ except Exception as e:
139
+ st.error(f"Error during video prediction: {str(e)}")
140
+ return None, None
141
+
142
+ def main():
143
+ with st.sidebar:
144
+ st.title("Deepfake Detection")
145
+ tab = st.radio("Select Input Type:", ["Image", "Video"])
146
+ if tab == "Image":
147
+ st.subheader("Analysis Visualization Options")
148
+ show_gradcam = st.checkbox("GradCAM", value=True)
149
+ show_aca = st.checkbox("ACA", value=False)
150
+ show_ela = st.checkbox("ELA", value=False)
151
+ if show_ela:
152
+ quality = st.slider("JPEG Quality", 0, 100, 95)
153
+ scale = st.slider("ELA Scale", 1, 50, 15)
154
+
155
+ models = load_models()
156
+
157
+ if tab == "Image":
158
+ st.header("Image Deepfake Detection")
159
+ num_cols = 1 + sum([show_gradcam, show_aca, show_ela])
160
+ cols = st.columns(num_cols)
161
+ col_idx = 0
162
+
163
+ with cols[col_idx]:
164
+ st.subheader("Input")
165
+ image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
166
+ if image is not None:
167
+ image = cv2.imdecode(np.frombuffer(image.read(), np.uint8), cv2.IMREAD_COLOR)
168
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
169
+ st.image(image, caption="Input", use_container_width=True)
170
+
171
+ if st.button("Analyze"):
172
+ with st.spinner("Processing..."):
173
+ confidences, cam_image = predict_image(image, models)
174
+ if show_gradcam:
175
+ col_idx += 1
176
+ with cols[col_idx]:
177
+ st.subheader("GradCAM")
178
+ if confidences and cam_image is not None:
179
+ st.image(cam_image, caption="Model Focus", use_container_width=True)
180
+ for label, conf in confidences.items():
181
+ st.progress(conf, text=f"{label}: {conf*100:.1f}%")
182
+ else:
183
+ st.warning("No face detected!")
184
+ if show_aca:
185
+ col_idx += 1
186
+ with cols[col_idx]:
187
+ st.subheader("ACA")
188
+ color_map = aca(image)
189
+ st.image(color_map, use_container_width=True)
190
+ if show_ela:
191
+ col_idx += 1
192
+ with cols[col_idx]:
193
+ st.subheader("ELA")
194
+ _, ela_map = perform_ela(image, quality=quality, scale=scale)
195
+ st.image(ela_map, use_container_width=True)
196
+ else:
197
+ st.header("Video Deepfake Detection")
198
+ col1, col2 = st.columns(2)
199
+ with col1:
200
+ st.subheader("Input")
201
+ video = st.file_uploader("Choose a video...", type=["mp4", "avi", "mov"])
202
+ if video is not None:
203
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4', dir='/home/appuser') as tmp_file:
204
+ tmp_file.write(video.read())
205
+ video_path = tmp_file.name
206
+ st.video(video)
207
+ if st.button("Analyze"):
208
+ with st.spinner("Processing..."):
209
+ try:
210
+ confidences, cam_image = predict_video(video_path, models)
211
+ with col2:
212
+ st.subheader("Results")
213
+ if confidences and cam_image is not None:
214
+ st.image(cam_image, caption="GradCAM", use_container_width=True)
215
+ for label, conf in confidences.items():
216
+ st.progress(conf, text=f"{label}: {conf*100:.1f}%")
217
+ else:
218
+ st.warning("No faces detected!")
219
+ finally:
220
+ if os.path.exists(video_path):
221
+ os.unlink(video_path)
222
+
223
+ if __name__ == "__main__":
224
+ main()
demo/run.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ APP_PID=
4
+ stopRunningProcess() {
5
+ if test ! "${APP_PID}" = '' && ps -p ${APP_PID} > /dev/null ; then
6
+ > /proc/1/fd/1 echo "Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}"
7
+ kill -TERM ${APP_PID}
8
+ > /proc/1/fd/1 echo "Waiting for ${COMMAND_PATH} to process SIGTERM signal"
9
+ wait ${APP_PID}
10
+ > /proc/1/fd/1 echo "All processes have stopped running"
11
+ else
12
+ > /proc/1/fd/1 echo "${COMMAND_PATH} was not started when the signal was sent or it has already been stopped"
13
+ fi
14
+ }
15
+
16
+ trap stopRunningProcess EXIT TERM
17
+
18
+ #HF workaround flags (ditch Xsrf flag locally)
19
+
20
+ streamlit run ${HOME}/blueprint/demo/app.py \
21
+ --server.address=0.0.0.0 \
22
+ --server.enableCORS=false \
23
+ --server.enableXsrfProtection=false &
24
+
25
+ APP_PID=${!}
26
+
27
+ wait ${APP_PID}
docs/api.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # API Reference
2
+
3
+ "::: blueprint.hello"
docs/assets/custom.css ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
2
+
3
+ :root {
4
+ --md-default-font: "Inter", sans-serif;
5
+ --md-code-font: "Fira Code", monospace;
6
+ --md-primary-font: "Inter", sans-serif;
7
+ }
docs/customization.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🎨 **Customization Guide**
2
+
3
+ This Blueprint is designed to be flexible and easily adaptable to your specific needs. This guide will walk you through some key areas you can customize to make the Blueprint your own.
4
+
5
+ ---
6
+
7
+ ## 🧠 **Changing the Model**
8
+
9
+
10
+
11
+ ## 📝 **Modifying the system Prompt**
12
+
13
+
14
+
15
+ ## 💡 Other Customization Ideas
16
+
17
+ - other ideas..
18
+
19
+
20
+ ## 🤝 **Contributing to the Blueprint**
21
+
22
+ Want to help improve or extend this Blueprint? Check out the **[Future Features & Contributions Guide](future-features-contributions.md)** to see how you can contribute your ideas, code, or feedback to make this Blueprint even better!
docs/future-features-contributions.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 **Future Features & Contributions**
2
+
3
+ This Blueprint is an evolving project designed to grow with the help of the open-source community. Whether you’re an experienced developer or just starting, there are many ways you can contribute and help shape the future of this tool.
4
+
5
+ ---
6
+
7
+ ## 🌟 **How You Can Contribute**
8
+
9
+ ### 🛠️ **Enhance the Blueprint**
10
+ - Check the [Issues](https://github.com/mozilla-ai/blueprint-template/issues) page to see if there are feature requests you'd like to implement
11
+ - Refer to our [Contribution Guide](https://github.com/mozilla-ai/blueprint-template/blob/main/CONTRIBUTING.md) for more details on contributions
12
+
13
+ ### 🎨 **Extensibility Ideas**
14
+
15
+ This Blueprint is designed to be a foundation you can build upon. By extending its capabilities, you can open the door to new applications, improve user experience, and adapt the Blueprint to address other use cases. Here are a few ideas for how you can expand its potential:
16
+
17
+
18
+ We’d love to see how you can enhance this Blueprint! If you create improvements or extend its capabilities, consider contributing them back to the project so others in the community can benefit from your work. Check out our [Contributions Guide](https://github.com/mozilla-ai/blueprint-template/blob/main/CONTRIBUTING.md) to get started!
19
+
20
+ ### 💡 **Share Your Ideas**
21
+ Got an idea for how this Blueprint could be improved? You can share your suggestions through [GitHub Discussions](https://github.com/mozilla-ai/blueprint-template/discussions).
22
+
23
+ ### 🌍 **Build New Blueprints**
24
+ This project is part of a larger initiative to create a collection of reusable starter code solutions that use open-source AI tools. If you’re inspired to create your own Blueprint, you can use the [Blueprint-template](https://github.com/new?template_name=Blueprint-template&template_owner=mozilla-ai) to get started.
25
+
26
+ ---
27
+
28
+ Your contributions help make this Blueprint better for everyone 🎉
docs/getting-started.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Get started with this Blueprint using one of the options below:
2
+
3
+ ---
4
+
5
+ ### **Option 1:**
6
+
7
+
8
+
9
+ ### **Option 2:**
docs/images/Blueprints-logo.png ADDED
docs/index.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # **Welcome to the Blueprint docs**
2
+
3
+ Blueprints are customizable workflows that help developers build AI applications using open-source tools and models
4
+
5
+ These docs are your companion to mastering this Blueprint.
6
+
7
+ ### Built with
8
+ - Python 3.10+
9
+ - Tool 1
10
+ - Tool 2
11
+
12
+
13
+ ---
14
+
15
+ ### 🚀 **Get Started Quickly**
16
+ #### _Start building the Blueprint in minutes:_
17
+ - **[Getting Started](getting-started.md):** Quick setup and installation instructions.
18
+
19
+ ### 🔍 **Understand the System**
20
+ #### _Dive deeper into how the Blueprint works:_
21
+ - **[Step-by-Step Guide](step-by-step-guide.md):** A detailed breakdown of the system’s design and workflow.
22
+ - **[API Reference](api.md):** Explore the technical details of the core modules.
23
+
24
+ ### 🎨 **Make It Yours**
25
+ #### _Customize the Blueprint to fit your needs:_
26
+ - **[Customization Guide](customization.md):** Tailor project parameters to fit your needs
27
+
28
+ ### 🌟 **Join the Community**
29
+ #### _Help shape the future of Blueprints:_
30
+ - **[Future Features & Contributions](future-features-contributions.md):** Learn about exciting upcoming features and how to contribute to the project.
31
+
32
+
33
+ Have more questions? Reach out to us on [GitHub Discussions](https://github.com/mozilla-ai/blueprint-template/discussions).
34
+
35
+ ---
36
+
37
+ ## **Why Blueprints?**
38
+
39
+ Blueprints are more than starter code—they’re your gateway to building AI-powered solutions with confidence. With step-by-step guidance, modular design, and open-source tools, we make AI accessible for developers of all skill levels.
docs/step-by-step-guide.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # **Step-by-Step Guide: How this Blueprint Works**
2
+
3
+
4
+ ---
5
+
6
+ ## **Overview**
7
+
8
+
9
+ ---
10
+
11
+ ## **Step 1**
12
+
13
+
14
+ ## **Step 2**
15
+
16
+
17
+ ## **Step 3**
18
+
19
+
20
+
21
+ ## 🎨 **Customizing the Blueprint**
22
+
23
+ To better understand how you can tailor this Blueprint to suit your specific needs, please visit the **[Customization Guide](customization.md)**.
24
+
25
+ ## 🤝 **Contributing to the Blueprint**
26
+
27
+ Want to help improve or extend this Blueprint? Check out the **[Future Features & Contributions Guide](future-features-contributions.md)** to see how you can contribute your ideas, code, or feedback to make this Blueprint even better!
images/Blueprints-logo.png ADDED
mkdocs.yml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ site_name: Blueprints Docs
2
+ repo_url: https://github.com/mozilla-ai/blueprint-template
3
+ repo_name: blueprint-template
4
+
5
+ nav:
6
+ - Home: index.md
7
+ - Getting Started: getting-started.md
8
+ - Step-by-Step Guide: step-by-step-guide.md
9
+ - Customization Guide: customization.md
10
+ - API Reference: api.md
11
+ - Future Features & Contributions: future-features-contributions.md
12
+
13
+ theme:
14
+ icon:
15
+ repo: fontawesome/brands/github
16
+ name: material
17
+ palette:
18
+ - scheme: default
19
+ primary: "#005F6F"
20
+ toggle:
21
+ icon: material/lightbulb
22
+ name: Switch to dark mode
23
+ - scheme: slate
24
+ primary: "#005F6F"
25
+ toggle:
26
+ icon: material/lightbulb-outline
27
+ name: Switch to light mode
28
+ extra_css:
29
+ - assets/custom.css
30
+
31
+ markdown_extensions:
32
+ - pymdownx.highlight:
33
+ anchor_linenums: true
34
+ line_spans: __span
35
+ pygments_lang_class: true
36
+ - pymdownx.inlinehilite
37
+ - pymdownx.snippets
38
+ - pymdownx.superfences
39
+
40
+ plugins:
41
+ - search
42
+ - mkdocstrings:
43
+ handlers:
44
+ python:
45
+ options:
46
+ show_root_heading: true
pyproject.toml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=48", "setuptools_scm[toml]>=6.3.1"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "blueprint"
7
+ readme = "README.md"
8
+ license = {text = "Apache-2.0"}
9
+ requires-python = ">=3.10"
10
+ dynamic = ["version"]
11
+ dependencies = [
12
+ "streamlit",
13
+ "torch>=2.0.0",
14
+ "opencv-python",
15
+ "numpy",
16
+ "dlib-binary",
17
+ "retinaface-pytorch",
18
+ "efficientnet_pytorch",
19
+ "albumentations",
20
+ "grad-cam==1.4.8",
21
+ "Pillow"
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ docs = [
26
+ "mkdocs",
27
+ "mkdocs-material",
28
+ "mkdocstrings-python",
29
+ ]
30
+
31
+ tests = [
32
+ "pytest>=8,<9",
33
+ "pytest-sugar>=0.9.6",
34
+ ]
35
+
36
+ [tool.setuptools.packages.find]
37
+ exclude = ["tests", "tests.*"]
38
+ where = ["src"]
39
+ namespaces = false
40
+
41
+ [tool.setuptools_scm]
src/blueprint/__init__.py ADDED
File without changes
src/blueprint/hello.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ def hello() -> str:
2
+ """
3
+ Greets the world
4
+
5
+ Returns:
6
+ str: "Hello, world!"
7
+ """
8
+ return "Hello, world!"
src/blueprint/model.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from efficientnet_pytorch import EfficientNet
4
+ from pytorch_grad_cam import GradCAMElementWise
5
+ from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
6
+
7
+ class Detector(nn.Module):
8
+ def __init__(self):
9
+ super(Detector, self).__init__()
10
+ self.net = EfficientNet.from_pretrained("efficientnet-b4", advprop=True, num_classes=2)
11
+
12
+ def forward(self, x):
13
+ x = self.net(x)
14
+ return x
15
+
16
+ def create_model(path="Weights/94_0.9485_val.tar", device=torch.device('cpu')):
17
+ model = Detector()
18
+ try:
19
+ if device.type == 'cuda':
20
+ model = model.half()
21
+ except:
22
+ model = model.float()
23
+ model = model.to(device)
24
+ if device == torch.device('cpu'):
25
+ cnn_sd = torch.load(path, map_location=torch.device('cpu'))["model"]
26
+ else:
27
+ cnn_sd = torch.load(path)["model"]
28
+ model.load_state_dict(cnn_sd)
29
+ model.eval()
30
+ return model
31
+
32
+ def create_cam(model):
33
+ target_layers = [model.net._blocks[-1]]
34
+ targets = [ClassifierOutputTarget(1)]
35
+ cam_algorithm = GradCAMElementWise
36
+ use_cuda = torch.cuda.is_available() and next(model.parameters()).is_cuda
37
+ cam = cam_algorithm(model=model, target_layers=target_layers, use_cuda=use_cuda)
38
+ return cam
src/blueprint/preprocess.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+
4
+ def extract_frames(filename, num_frames, model, image_size=(380, 380)):
5
+ cap = cv2.VideoCapture(filename)
6
+ if not cap.isOpened():
7
+ return [], []
8
+
9
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
10
+ frame_idxs = np.linspace(0, frame_count - 1, min(num_frames, frame_count), dtype=int)
11
+
12
+ croppedfaces, idx_list = [], []
13
+ for idx in frame_idxs:
14
+ ret = cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
15
+ if not ret:
16
+ continue
17
+ ret, frame = cap.read()
18
+ if not ret:
19
+ continue
20
+
21
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
22
+ faces = extract_face(frame, model, image_size)
23
+ if faces:
24
+ croppedfaces.extend(faces)
25
+ idx_list.extend([idx] * len(faces))
26
+
27
+ cap.release()
28
+ return croppedfaces, idx_list
29
+
30
+ def extract_face(frame, model, image_size=(380, 380)):
31
+ faces = model.predict_jsons(frame)
32
+ if len(faces[0]['bbox']) == 0:
33
+ scale_factor = 0.5
34
+ small_frame = cv2.resize(frame, None, fx=scale_factor, fy=scale_factor)
35
+ faces = model.predict_jsons(small_frame)
36
+ if len(faces[0]['bbox']) == 0:
37
+ return []
38
+ for face in faces:
39
+ face['bbox'] = [coord/scale_factor for coord in face['bbox']]
40
+
41
+ croppedfaces = []
42
+ for face_idx in range(len(faces)):
43
+ x0, y0, x1, y1 = faces[face_idx]['bbox']
44
+ bbox = np.array([[x0, y0], [x1, y1]])
45
+ face = crop_face(frame, None, bbox, False, crop_by_bbox=True, only_img=True, phase='test')
46
+ croppedfaces.append(cv2.resize(face, dsize=image_size).transpose((2, 0, 1)))
47
+
48
+ return croppedfaces
49
+
50
+ def crop_face(img, landmark=None, bbox=None, margin=False, crop_by_bbox=True, abs_coord=False, only_img=False, phase='test'):
51
+ assert phase in ['train', 'val', 'test']
52
+ assert landmark is not None or bbox is not None
53
+
54
+ H, W = len(img), len(img[0])
55
+
56
+ if crop_by_bbox:
57
+ x0, y0 = bbox[0]
58
+ x1, y1 = bbox[1]
59
+ w = x1 - x0
60
+ h = y1 - y0
61
+ w0_margin = w/4
62
+ w1_margin = w/4
63
+ h0_margin = h/4
64
+ h1_margin = h/4
65
+ else:
66
+ x0, y0 = landmark[:68,0].min(), landmark[:68,1].min()
67
+ x1, y1 = landmark[:68,0].max(), landmark[:68,1].max()
68
+ w = x1 - x0
69
+ h = y1 - y0
70
+ w0_margin = w/8
71
+ w1_margin = w/8
72
+ h0_margin = h/2
73
+ h1_margin = h/5
74
+
75
+ if margin:
76
+ w0_margin *= 4
77
+ w1_margin *= 4
78
+ h0_margin *= 2
79
+ h1_margin *= 2
80
+ elif phase == 'train':
81
+ rand_factor = np.random.rand(4) * 0.6 + 0.2
82
+ w0_margin *= rand_factor[0]
83
+ w1_margin *= rand_factor[1]
84
+ h0_margin *= rand_factor[2]
85
+ h1_margin *= rand_factor[3]
86
+ else:
87
+ w0_margin *= 0.5
88
+ w1_margin *= 0.5
89
+ h0_margin *= 0.5
90
+ h1_margin *= 0.5
91
+
92
+ y0_new = max(0, int(y0-h0_margin))
93
+ y1_new = min(H, int(y1+h1_margin)+1)
94
+ x0_new = max(0, int(x0-w0_margin))
95
+ x1_new = min(W, int(x1+w1_margin)+1)
96
+
97
+ img_cropped = img[y0_new:y1_new, x0_new:x1_new]
98
+
99
+ if only_img:
100
+ return img_cropped
101
+
102
+ if landmark is not None:
103
+ landmark_cropped = np.zeros_like(landmark)
104
+ for i, (p,q) in enumerate(landmark):
105
+ landmark_cropped[i] = [p-x0_new, q-y0_new]
106
+ else:
107
+ landmark_cropped = None
108
+
109
+ if bbox is not None:
110
+ bbox_cropped = np.zeros_like(bbox)
111
+ for i, (p,q) in enumerate(bbox):
112
+ bbox_cropped[i] = [p-x0_new, q-y0_new]
113
+ else:
114
+ bbox_cropped = None
115
+
116
+ if abs_coord:
117
+ return img_cropped, landmark_cropped, bbox_cropped, (y0-y0_new, x0-x0_new, y1_new-y1, x1_new-x1), y0_new, y1_new, x0_new, x1_new
118
+ else:
119
+ return img_cropped, landmark_cropped, bbox_cropped, (y0-y0_new, x0-x0_new, y1_new-y1, x1_new-x1)
tests/unit/test_hello.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from blueprint.hello import hello
2
+
3
+
4
+ def test_hello():
5
+ assert hello() == "Hello, world!"