Spaces:
Sleeping
Sleeping
Commit
·
e11256b
1
Parent(s):
be8e7fc
api integrated
Browse files- .dockerignore +6 -0
- .github/ISSUE_TEMPLATE/bug_report.md +35 -0
- .github/ISSUE_TEMPLATE/custom.md +30 -0
- .github/ISSUE_TEMPLATE/feature_request.md +23 -0
- .github/auto-label.json5 +21 -0
- .github/auto_label_pr.yml +63 -0
- .github/dependabot.yml +11 -0
- .github/release.yml +47 -0
- .github/workflows/auto-label-issue.yaml +18 -0
- .github/workflows/autolabel-pr.yaml +22 -0
- .github/workflows/docker.yaml +95 -0
- .github/workflows/documentation.yml +43 -0
- .github/workflows/mirror_to_gitlab.yml +23 -0
- .github/workflows/pypi.yml +80 -0
- .github/workflows/pytest.yaml +46 -0
- .github/workflows/release_on_tag.yaml +72 -0
- .github/workflows/ruff.yml +11 -0
- .gitignore +242 -0
- CHANGELOG.md +34 -0
- CONTRIBUTING.md +59 -0
- Dockerfile +56 -0
- LICENSE +674 -0
- Makefile +20 -0
- app.py +82 -0
- pyproject.toml +73 -0
- requirements.txt +17 -0
- scraibe/__init__.py +11 -0
- scraibe/_version.py +1 -0
- scraibe/audio.py +146 -0
- scraibe/autotranscript.py +358 -0
- scraibe/cli.py +160 -0
- scraibe/diarisation.py +309 -0
- scraibe/hallucinations.py +95 -0
- scraibe/misc.py +89 -0
- scraibe/transcriber.py +461 -0
- scraibe/transcript_exporter.py +321 -0
- source/conf.py +84 -0
- source/index.rst +21 -0
- source/modules.rst +7 -0
- tests/audio_test_1.mp4 +0 -0
- tests/audio_test_2.mp4 +0 -0
- tests/test_audio.py +96 -0
- tests/test_autotranscript.py +52 -0
- tests/test_diarisation.py +32 -0
- tests/test_transcriber.py +80 -0
.dockerignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
scraibe/*__pycache__
|
2 |
+
scraibe/app/*__pycache__
|
3 |
+
scraibe/.pyannotetoken
|
4 |
+
.git
|
5 |
+
.gitignore
|
6 |
+
.github
|
.github/ISSUE_TEMPLATE/bug_report.md
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Bug report
|
3 |
+
about: Create a report to help us improve
|
4 |
+
title: "[BUG]"
|
5 |
+
labels: bug
|
6 |
+
assignees: ''
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
## Description 🐛
|
11 |
+
Please provide a clear and concise description of the bug. What went wrong?
|
12 |
+
|
13 |
+
## Steps to Reproduce 🔍
|
14 |
+
Steps to reproduce the behavior:
|
15 |
+
1. Go to '...'
|
16 |
+
2. Run command '....'
|
17 |
+
3. Provide input '....'
|
18 |
+
4. See error
|
19 |
+
|
20 |
+
## Expected Behavior 🤔
|
21 |
+
What did you expect to happen instead?
|
22 |
+
|
23 |
+
## Screenshots or Logs 📸
|
24 |
+
If applicable, add screenshots or logs to help explain your problem. This can include terminal output or error messages.
|
25 |
+
|
26 |
+
## Environment 🖥️
|
27 |
+
- **OS**: [e.g., Ubuntu 20.04]
|
28 |
+
- **Python Version**: [e.g., 3.9]
|
29 |
+
- **PyTorch Version**: [e.g., 2.0]
|
30 |
+
- **CUDA Version** (if applicable): [e.g., 11.7]
|
31 |
+
- **ScrAIbe Version**: [e.g., 1.0.0]
|
32 |
+
- **Installation Type**: [e.g., pip, GitHub, Docker, etc.]
|
33 |
+
|
34 |
+
## Additional Context 📝
|
35 |
+
Add any other context about the problem here. For example, information about custom models or configurations, related issues, or anything else that might be helpful.
|
.github/ISSUE_TEMPLATE/custom.md
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Custom issue template
|
3 |
+
about: Describe this issue template's purpose here.
|
4 |
+
title: "[CUSTOM] "
|
5 |
+
labels: ''
|
6 |
+
assignees: ''
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
## Description 📝
|
11 |
+
Provide a detailed description of the issue or request. Explain the context, the problem, or the question you have.
|
12 |
+
|
13 |
+
## Objective 🎯
|
14 |
+
What do you hope to achieve with this issue? Are you looking for guidance, proposing a discussion, or something else?
|
15 |
+
|
16 |
+
## Relevant Information 📂
|
17 |
+
Include any relevant details, such as:
|
18 |
+
- Code snippets
|
19 |
+
- Links to related documentation or issues
|
20 |
+
- Configuration files
|
21 |
+
- Screenshots or diagrams
|
22 |
+
|
23 |
+
## Steps to Reproduce or Reference 🔍
|
24 |
+
If applicable, provide steps to reproduce the issue or reference specific parts of the project that are relevant to your issue.
|
25 |
+
|
26 |
+
## Proposed Next Steps 🚀
|
27 |
+
What do you propose as the next steps for addressing this issue? Do you need help, or are you suggesting a specific course of action?
|
28 |
+
|
29 |
+
## Additional Context 📝
|
30 |
+
Add any other context that might help understand the issue. This could include environmental details, related discussions, or any other relevant information.
|
.github/ISSUE_TEMPLATE/feature_request.md
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Feature request
|
3 |
+
about: Suggest an idea for this project
|
4 |
+
title: "[FEATURE]"
|
5 |
+
labels: feature
|
6 |
+
assignees: ''
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
## Description 📝
|
11 |
+
Provide a clear and concise description of the feature or enhancement you are proposing. What problem does it solve, or what capability does it add?
|
12 |
+
|
13 |
+
## Use Case 💡
|
14 |
+
Explain the use case(s) for this feature. How would it benefit you or others? Include any relevant examples or scenarios.
|
15 |
+
|
16 |
+
## Proposed Solution 🚀
|
17 |
+
Describe your proposed solution in detail. How would the feature work? If you have an idea of how to implement it, include that here. Code snippets or references to other projects can be helpful.
|
18 |
+
|
19 |
+
## Alternatives Considered 🔄
|
20 |
+
Have you considered any alternative approaches or solutions? If so, please describe them and explain why they wouldn't be as effective.
|
21 |
+
|
22 |
+
## Additional Context 📝
|
23 |
+
Add any other context, screenshots, or mockups that might help clarify your request. This could include links to relevant discussions, related issues, or other resources.
|
.github/auto-label.json5
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
labelsSynonyms: {
|
3 |
+
bug: ['error', 'need fix', 'not working', 'failure', 'crash', 'problem', 'issue', 'defect', 'glitch', 'fault', 'anomaly'],
|
4 |
+
enhancement: ['upgrade', 'update', 'improve', 'feature request', 'new feature', 'enhance', 'extension', 'add-on', 'improvement'],
|
5 |
+
"help wanted": ['help', 'how can i', 'assistance needed', 'support needed', 'question', 'guidance', 'aid', 'need assistance', 'advice', 'instruction'],
|
6 |
+
documentation: ['docs', 'Readme', 'documentation', 'guide', 'manual', 'instructions', 'how-to', 'reference', 'tutorial', 'specification'],
|
7 |
+
docker: ['compose', 'Dockerfile', 'container', 'docker-compose', 'image', 'docker setup', 'kubernetes', 'docker swarm', 'containerization'],
|
8 |
+
performance: ['slow', 'lag', 'performance', 'speed', 'optimization', 'tuning', 'efficiency', 'latency', 'improve performance', 'boost', 'performance issue'],
|
9 |
+
security: ['vulnerability', 'exploit', 'attack', 'breach', 'security', 'protection', 'patch', 'secure', 'threat', 'risk', 'malware'],
|
10 |
+
ui: ['user interface', 'ui', 'ux', 'design', 'layout', 'front-end', 'visual', 'interface', 'experience', 'aesthetic', 'theme', 'style'],
|
11 |
+
test: ['test', 'testing', 'unit test', 'integration test', 'e2e test', 'automated test', 'test case', 'test suite', 'qa', 'quality assurance'],
|
12 |
+
compatibility: ['compatible', 'incompatible', 'version', 'compatibility', 'interop', 'support', 'versioning', 'cross-platform', 'integration', 'compatibility issue']
|
13 |
+
},
|
14 |
+
labelsNotAllowed: [
|
15 |
+
'duplicate',
|
16 |
+
'good first issue',
|
17 |
+
'invalid'
|
18 |
+
],
|
19 |
+
//defaultLabels: ['triage'],
|
20 |
+
ignoreComments: true
|
21 |
+
}
|
.github/auto_label_pr.yml
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# .github/labeler.yml
|
2 |
+
|
3 |
+
# Label for documentation changes
|
4 |
+
documentation:
|
5 |
+
- changed-files:
|
6 |
+
- any-glob-to-any-file:
|
7 |
+
- 'docs/**'
|
8 |
+
- 'README.md'
|
9 |
+
- 'CHANGELOG.md'
|
10 |
+
- 'CONTRIBUTING.md'
|
11 |
+
- 'Makefile'
|
12 |
+
- 'Pictures'
|
13 |
+
|
14 |
+
|
15 |
+
# Label for Docker changes
|
16 |
+
docker:
|
17 |
+
- changed-files:
|
18 |
+
- any-glob-to-any-file:
|
19 |
+
- '*docker*'
|
20 |
+
- 'Docker*'
|
21 |
+
|
22 |
+
# Label for release-related changes
|
23 |
+
release:
|
24 |
+
- changed-files:
|
25 |
+
- any-glob-to-any-file:
|
26 |
+
- 'scraibe/**'
|
27 |
+
- 'pyproject.toml'
|
28 |
+
- 'LICENCE'
|
29 |
+
|
30 |
+
tests:
|
31 |
+
- changed-files:
|
32 |
+
- any-glob-to-any-file:
|
33 |
+
- 'test/**'
|
34 |
+
|
35 |
+
workflows:
|
36 |
+
- changed-files:
|
37 |
+
- any-glob-to-any-file:
|
38 |
+
- '.github/workflows/*'
|
39 |
+
- '.github/*'
|
40 |
+
|
41 |
+
github:
|
42 |
+
- changed-files:
|
43 |
+
- any-glob-to-any-file:
|
44 |
+
- '.gitignore'
|
45 |
+
- '.github/ISSUE_TEMPLATE/*'
|
46 |
+
|
47 |
+
dependencies:
|
48 |
+
- changed-files:
|
49 |
+
- any-glob-to-any-file:
|
50 |
+
- 'requirements.txt'
|
51 |
+
- 'environment.yml'
|
52 |
+
- 'pyproject.toml'
|
53 |
+
- head-branch: ['^dependencies', 'dependencies', '^dependency', 'dependency']
|
54 |
+
|
55 |
+
feature:
|
56 |
+
- head-branch: ['^feature', 'feature']
|
57 |
+
|
58 |
+
patch:
|
59 |
+
- head-branch: ['^patch', 'patch', '^bug', 'bug']
|
60 |
+
|
61 |
+
ignore-pr-title-for-release:
|
62 |
+
- head-branch: ['develop']
|
63 |
+
- base-branch: ['main']
|
.github/dependabot.yml
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# To get started with Dependabot version updates, you'll need to specify which
|
2 |
+
# package ecosystems to update and where the package manifests are located.
|
3 |
+
# Please see the documentation for all configuration options:
|
4 |
+
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
5 |
+
|
6 |
+
version: 2
|
7 |
+
updates:
|
8 |
+
- package-ecosystem: "pip" # See documentation for possible values
|
9 |
+
directory: "/" # Location of package manifests
|
10 |
+
schedule:
|
11 |
+
interval: "weekly"
|
.github/release.yml
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#Automatically generated release notes from GIthub used by softprops/action-gh-release@v2 in .github/workflows/release.yaml
|
2 |
+
|
3 |
+
changelog:
|
4 |
+
exclude:
|
5 |
+
labels:
|
6 |
+
- ignore-for-release
|
7 |
+
- ignore-pr-title-for-release
|
8 |
+
- workflows
|
9 |
+
- github
|
10 |
+
- documentation
|
11 |
+
authors:
|
12 |
+
- octocat
|
13 |
+
- github-actions[bot]
|
14 |
+
|
15 |
+
categories:
|
16 |
+
- title: New Features 🎉
|
17 |
+
labels:
|
18 |
+
- enhancement
|
19 |
+
- feature
|
20 |
+
- Semver-Minor
|
21 |
+
|
22 |
+
- title: Bug Fixes 🐛
|
23 |
+
labels:
|
24 |
+
- bug
|
25 |
+
- fix
|
26 |
+
- patch
|
27 |
+
|
28 |
+
- title: Dependency Updates 📦
|
29 |
+
labels:
|
30 |
+
- dependency
|
31 |
+
- dependencies
|
32 |
+
- dependency-update
|
33 |
+
|
34 |
+
- title: Breaking Changes 🛠
|
35 |
+
labels:
|
36 |
+
- breaking-change
|
37 |
+
- Semver-Major
|
38 |
+
|
39 |
+
- title: Container and Compose Updates 🐳
|
40 |
+
labels:
|
41 |
+
- docker
|
42 |
+
- compose
|
43 |
+
- docker-compose
|
44 |
+
|
45 |
+
- title: Other Changes 🔧
|
46 |
+
labels:
|
47 |
+
- "*"
|
.github/workflows/auto-label-issue.yaml
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Labeling new issue
|
2 |
+
on:
|
3 |
+
issues:
|
4 |
+
types: [opened, reopened]
|
5 |
+
|
6 |
+
jobs:
|
7 |
+
build:
|
8 |
+
runs-on: ubuntu-latest
|
9 |
+
steps:
|
10 |
+
- uses: actions/checkout@v4
|
11 |
+
with:
|
12 |
+
sparse-checkout: |
|
13 |
+
.github/auto-label.json5
|
14 |
+
sparse-checkout-cone-mode: false
|
15 |
+
- uses: Renato66/auto-label@v3
|
16 |
+
with:
|
17 |
+
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
18 |
+
configuration-file: .github/auto-label.json5
|
.github/workflows/autolabel-pr.yaml
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Auto Label PRs
|
2 |
+
|
3 |
+
on:
|
4 |
+
pull_request:
|
5 |
+
types: [opened, synchronize, reopened, edited]
|
6 |
+
|
7 |
+
jobs:
|
8 |
+
label:
|
9 |
+
runs-on: ubuntu-latest
|
10 |
+
permissions:
|
11 |
+
contents: read
|
12 |
+
pull-requests: write
|
13 |
+
outputs:
|
14 |
+
all-labels: ${{ steps.label-the-PR.outputs.all-labels }}
|
15 |
+
steps:
|
16 |
+
- name: Apply Labels
|
17 |
+
id: label-the-PR
|
18 |
+
uses: actions/labeler@v5
|
19 |
+
with:
|
20 |
+
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
21 |
+
configuration-path: .github/auto_label_pr.yml
|
22 |
+
sync-labels: true
|
.github/workflows/docker.yaml
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This workflow uses actions that are not certified by GitHub.
|
2 |
+
# They are provided by a third-party and are governed by
|
3 |
+
# separate terms of service, privacy policy, and support
|
4 |
+
# documentation.
|
5 |
+
|
6 |
+
# GitHub recommends pinning actions to a commit SHA.
|
7 |
+
# To get a newer version, you will need to update the SHA.
|
8 |
+
# You can also reference a tag or branch, but the action may change without warning.
|
9 |
+
|
10 |
+
name: Publish Docker image
|
11 |
+
|
12 |
+
on:
|
13 |
+
|
14 |
+
push:
|
15 |
+
tags:
|
16 |
+
- v*
|
17 |
+
|
18 |
+
workflow_dispatch:
|
19 |
+
|
20 |
+
env:
|
21 |
+
image: hadr0n/scraibe
|
22 |
+
|
23 |
+
jobs:
|
24 |
+
push_to_registry:
|
25 |
+
name: Push Docker image to Docker Hub
|
26 |
+
runs-on: ubuntu-latest
|
27 |
+
permissions:
|
28 |
+
packages: write
|
29 |
+
contents: read
|
30 |
+
security-events: write
|
31 |
+
steps:
|
32 |
+
- name: Check out the repo
|
33 |
+
uses: actions/checkout@v4
|
34 |
+
with:
|
35 |
+
fetch-tags: true
|
36 |
+
fetch-depth: 0
|
37 |
+
|
38 |
+
- name: Get Version Tag
|
39 |
+
id: version
|
40 |
+
run: |
|
41 |
+
echo "tag=$(git describe --tags --abbrev=0)" >> $GITHUB_OUTPUT
|
42 |
+
|
43 |
+
- name: Overwrite label tag
|
44 |
+
run: sed -i 's/LABEL version=".*"/LABEL version="'${{ steps.version.outputs.tag }}'"/' Dockerfile
|
45 |
+
|
46 |
+
- name: Test name and tag
|
47 |
+
run: |
|
48 |
+
echo "${{ env.image }}:latest,${{ env.image }}:${{ steps.version.outputs.tag }}"
|
49 |
+
|
50 |
+
- name: Log in to Docker Hub
|
51 |
+
uses: docker/login-action@v3
|
52 |
+
with:
|
53 |
+
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
54 |
+
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
55 |
+
|
56 |
+
- name: Build and push Docker image
|
57 |
+
id: push
|
58 |
+
uses: docker/build-push-action@v5
|
59 |
+
with:
|
60 |
+
context: .
|
61 |
+
file: ./Dockerfile
|
62 |
+
push: true
|
63 |
+
tags: "${{ env.image }}:latest,${{ env.image }}:${{ steps.version.outputs.tag }}"
|
64 |
+
|
65 |
+
- name: SBOM Generation
|
66 |
+
uses: anchore/sbom-action@v0
|
67 |
+
with:
|
68 |
+
image: ${{ env.image }}:latest
|
69 |
+
|
70 |
+
- name: Scan image
|
71 |
+
id: scan
|
72 |
+
uses: anchore/scan-action@v3
|
73 |
+
with:
|
74 |
+
image: ${{ env.image }}:latest
|
75 |
+
fail-build: false
|
76 |
+
|
77 |
+
- name: upload Anchore scan SARIF report
|
78 |
+
uses: github/codeql-action/upload-sarif@v3
|
79 |
+
with:
|
80 |
+
sarif_file: ${{ steps.scan.outputs.sarif }}
|
81 |
+
|
82 |
+
# - name: Inspect action SARIF report
|
83 |
+
# run: cat ${{ steps.scan.outputs.sarif }}
|
84 |
+
|
85 |
+
- uses: actions/upload-artifact@v4
|
86 |
+
with:
|
87 |
+
name: SARIF report
|
88 |
+
path: ${{ steps.scan.outputs.sarif }}
|
89 |
+
|
90 |
+
# - name: Generate artifact attestation
|
91 |
+
# uses: actions/attest-build-provenance@v1
|
92 |
+
# with:
|
93 |
+
# subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
|
94 |
+
# subject-digest: ${{ steps.push.outputs.digest }}
|
95 |
+
# push-to-registry: false
|
.github/workflows/documentation.yml
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: documentation
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
tags:
|
6 |
+
- 'v*.*.*'
|
7 |
+
workflow_dispatch:
|
8 |
+
|
9 |
+
permissions:
|
10 |
+
contents: write
|
11 |
+
|
12 |
+
jobs:
|
13 |
+
docs:
|
14 |
+
runs-on: ubuntu-latest
|
15 |
+
steps:
|
16 |
+
- uses: actions/checkout@v4
|
17 |
+
- uses: actions/setup-python@v3
|
18 |
+
with:
|
19 |
+
python-version: 3.9
|
20 |
+
- name: Install dependencies
|
21 |
+
run: |
|
22 |
+
sudo apt-get install libsndfile1-dev
|
23 |
+
pip install --upgrade pip
|
24 |
+
pip install -r requirements.txt
|
25 |
+
pip install --upgrade sphinx sphinx_rtd_theme myst-parser
|
26 |
+
pip install --upgrade markdown-it-py[plugins]
|
27 |
+
pip install --upgrade mdit-py-plugins
|
28 |
+
|
29 |
+
- name: Sphinx build
|
30 |
+
run: |
|
31 |
+
cp README.md ./source/README.md
|
32 |
+
cp LICENSE ./source/LICENSE
|
33 |
+
cp -r Pictures ./source/Pictures
|
34 |
+
sphinx-apidoc -o source scraibe/
|
35 |
+
sphinx-build -M html source docs
|
36 |
+
make html
|
37 |
+
- name: Deploy to GitHub Pages
|
38 |
+
uses: peaceiris/actions-gh-pages@v3
|
39 |
+
with:
|
40 |
+
publish_branch: gh-pages
|
41 |
+
github_token: ${{ secrets.TOKEN_GH }}
|
42 |
+
publish_dir: ./docs/html
|
43 |
+
force_orphan: true
|
.github/workflows/mirror_to_gitlab.yml
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Mirror and run GitLab CI
|
2 |
+
|
3 |
+
on: [push, delete]
|
4 |
+
|
5 |
+
jobs:
|
6 |
+
build:
|
7 |
+
runs-on: ubuntu-latest
|
8 |
+
steps:
|
9 |
+
- uses: actions/checkout@v3
|
10 |
+
with:
|
11 |
+
fetch-depth: 0
|
12 |
+
- name: Mirror + trigger CI
|
13 |
+
uses: SvanBoxel/gitlab-mirror-and-ci-action@master
|
14 |
+
with:
|
15 |
+
args: "https://git-dmz.thuenen.de/kida/i2-skills-beratungsstelle/active-service-requests/scraibe/scraibe"
|
16 |
+
env:
|
17 |
+
FOLLOW_TAGS: "true"
|
18 |
+
FORCE_PUSH: "true"
|
19 |
+
GITLAB_HOSTNAME: "git-dmz.thuenen.de"
|
20 |
+
GITLAB_USERNAME: ${{ secrets.GITLAB_USERNAME }}
|
21 |
+
GITLAB_PASSWORD: ${{ secrets.GITLAB_PASSWORD }}
|
22 |
+
GITLAB_PROJECT_ID: ${{ secrets.GITLAB_PROJECT_ID }}
|
23 |
+
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
|
.github/workflows/pypi.yml
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Publish Python 🐍 distribution 📦 to PyPI and TestPyPI
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
tags:
|
6 |
+
- 'v*.*.*'
|
7 |
+
branches:
|
8 |
+
- "develop"
|
9 |
+
paths:
|
10 |
+
- "scraibe/**"
|
11 |
+
- "pyproject.toml"
|
12 |
+
|
13 |
+
workflow_dispatch:
|
14 |
+
inputs:
|
15 |
+
test:
|
16 |
+
description: "Run tests"
|
17 |
+
default: true
|
18 |
+
type: boolean
|
19 |
+
publish_to_pypi:
|
20 |
+
description: "Publish to PyPI"
|
21 |
+
default: false
|
22 |
+
type: boolean
|
23 |
+
|
24 |
+
jobs:
|
25 |
+
Build-and-publish-to-Test-PyPI:
|
26 |
+
if: github.event_name != 'workflow_dispatch' || github.event.inputs.test == 'true'
|
27 |
+
runs-on: ubuntu-latest
|
28 |
+
steps:
|
29 |
+
- uses: actions/checkout@v4
|
30 |
+
with:
|
31 |
+
fetch-depth: '0'
|
32 |
+
- name: Set up Poetry 📦
|
33 |
+
uses: JRubics/[email protected]
|
34 |
+
with:
|
35 |
+
pypi_token: ${{ secrets.TEST_PYPI_API_TOKEN }}
|
36 |
+
plugins: "poetry-dynamic-versioning"
|
37 |
+
repository_name: "scraibe"
|
38 |
+
repository_url: "https://test.pypi.org/legacy/"
|
39 |
+
|
40 |
+
Test-PyPi-install:
|
41 |
+
name: Test Installation from TestPyPI
|
42 |
+
needs: Build-and-publish-to-Test-PyPI
|
43 |
+
runs-on: ubuntu-latest
|
44 |
+
strategy:
|
45 |
+
matrix:
|
46 |
+
python-version: [3.9, 3.11, 3.12]
|
47 |
+
steps:
|
48 |
+
- uses: actions/checkout@v4
|
49 |
+
- name: Set up Python ${{ matrix.python-version }}
|
50 |
+
uses: actions/setup-python@v5
|
51 |
+
with:
|
52 |
+
python-version: ${{ matrix.python-version }}
|
53 |
+
- name: Install package
|
54 |
+
run: |
|
55 |
+
pip install -U setuptools
|
56 |
+
pip install -r requirements.txt
|
57 |
+
python3 -m pip install --no-deps --pre --index-url https://test.pypi.org/simple/ scraibe>=0.1.3
|
58 |
+
python3 -c "import scraibe; print(scraibe.__version__)"
|
59 |
+
|
60 |
+
publish-to-pypi:
|
61 |
+
name: Publish to PyPI
|
62 |
+
needs: Test-PyPi-install
|
63 |
+
runs-on: ubuntu-latest
|
64 |
+
if: |
|
65 |
+
always() &&
|
66 |
+
(( needs.Build-and-publish-to-Test-PyPI.result != 'failure' &&
|
67 |
+
needs.Test-PyPi-install.result != 'failure' ) ||
|
68 |
+
((github.event_name == 'workflow_dispatch' &&
|
69 |
+
github.event.inputs.publish_to_pypi == 'true')))
|
70 |
+
steps:
|
71 |
+
- name: Checkout Repository (Develop)
|
72 |
+
uses: actions/checkout@v4
|
73 |
+
with:
|
74 |
+
fetch-depth: '0'
|
75 |
+
- name: Set up Poetry 📦
|
76 |
+
uses: JRubics/[email protected]
|
77 |
+
with:
|
78 |
+
pypi_token: ${{ secrets.PYPI_API_TOKEN }}
|
79 |
+
plugins: "poetry-dynamic-versioning"
|
80 |
+
repository_name: "scraibe"
|
.github/workflows/pytest.yaml
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Run Tests
|
2 |
+
|
3 |
+
on:
|
4 |
+
pull_request:
|
5 |
+
branches:
|
6 |
+
- main
|
7 |
+
- develop
|
8 |
+
paths:
|
9 |
+
- scraibe/**
|
10 |
+
- pyproject.toml
|
11 |
+
- requirements.txt
|
12 |
+
- test/**
|
13 |
+
workflow_dispatch:
|
14 |
+
|
15 |
+
jobs:
|
16 |
+
pytest:
|
17 |
+
runs-on: ubuntu-latest
|
18 |
+
|
19 |
+
steps:
|
20 |
+
- name: Checkout
|
21 |
+
uses: actions/checkout@v3
|
22 |
+
with:
|
23 |
+
fetch-depth: 0
|
24 |
+
|
25 |
+
- name: Setup Python
|
26 |
+
uses: actions/setup-python@v3
|
27 |
+
with:
|
28 |
+
python-version: 3.9
|
29 |
+
|
30 |
+
- name: Install Dependencies
|
31 |
+
run: |
|
32 |
+
|
33 |
+
sudo apt update && sudo apt upgrade
|
34 |
+
python -m pip install --upgrade pip
|
35 |
+
pip install -r requirements.txt
|
36 |
+
pip install .
|
37 |
+
sudo apt-get install libsndfile1-dev
|
38 |
+
sudo apt-get install ffmpeg
|
39 |
+
pip install pytest
|
40 |
+
|
41 |
+
- name: Run pytest
|
42 |
+
env:
|
43 |
+
HF_TOKEN : ${{ secrets.HF_TOKEN }}
|
44 |
+
run: |
|
45 |
+
pytest
|
46 |
+
|
.github/workflows/release_on_tag.yaml
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: release
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
tags:
|
6 |
+
- 'v*.*.*'
|
7 |
+
|
8 |
+
jobs:
|
9 |
+
build-on-workflow:
|
10 |
+
runs-on: ubuntu-latest
|
11 |
+
if: |
|
12 |
+
github.event_name == 'workflow_run' &&
|
13 |
+
github.event.workflow_run.conclusion == 'success'
|
14 |
+
steps:
|
15 |
+
- name: Checkout
|
16 |
+
uses: actions/checkout@v4
|
17 |
+
with:
|
18 |
+
fetch-depth: 0 # Ensure all history is fetched
|
19 |
+
ref: main
|
20 |
+
|
21 |
+
- name: Get Latest Tag
|
22 |
+
id: get-latest-tag
|
23 |
+
if:
|
24 |
+
run: |
|
25 |
+
git fetch --tags
|
26 |
+
latest_tag=$(git describe --tags `git rev-list --tags --max-count=1`)
|
27 |
+
echo "latest_tag=$latest_tag" >> $GITHUB_OUTPUT
|
28 |
+
|
29 |
+
- name: Release from Workflow Run
|
30 |
+
if: |
|
31 |
+
github.event_name == 'workflow_run' &&
|
32 |
+
github.event.workflow_run.conclusion == 'success'
|
33 |
+
uses: softprops/action-gh-release@v2
|
34 |
+
with:
|
35 |
+
generate_release_notes: true
|
36 |
+
append_body: true
|
37 |
+
tag_name: ${{ steps.get-latest-tag.outputs.latest_tag }}
|
38 |
+
|
39 |
+
build-on-tag:
|
40 |
+
runs-on: ubuntu-latest
|
41 |
+
if: startsWith(github.ref, 'refs/tags/')
|
42 |
+
|
43 |
+
steps:
|
44 |
+
- name: Checkout
|
45 |
+
uses: actions/checkout@v4
|
46 |
+
with:
|
47 |
+
fetch-depth: 0 # Ensure all history is fetched
|
48 |
+
ref: main
|
49 |
+
- name: Release from Tag Push
|
50 |
+
uses: softprops/action-gh-release@v2
|
51 |
+
with:
|
52 |
+
generate_release_notes: true
|
53 |
+
append_body: true
|
54 |
+
|
55 |
+
write_changelog:
|
56 |
+
runs-on: ubuntu-latest
|
57 |
+
needs: [build-on-workflow, build-on-tag]
|
58 |
+
if: |
|
59 |
+
always() &&
|
60 |
+
(needs.build-on-workflow.result == 'success' || needs.build-on-tag.result == 'success' )
|
61 |
+
steps:
|
62 |
+
- name: Checkout
|
63 |
+
uses: actions/checkout@v4
|
64 |
+
with:
|
65 |
+
fetch-depth: 0 # Ensure all history is fetched
|
66 |
+
ref: main
|
67 |
+
|
68 |
+
- name: Write CHANGELOG.md
|
69 |
+
uses: rhysd/changelog-from-release/action@v3
|
70 |
+
with:
|
71 |
+
file: CHANGELOG.md
|
72 |
+
github_token: ${{ secrets.GITHUB_TOKEN }}
|
.github/workflows/ruff.yml
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Ruff
|
2 |
+
on:
|
3 |
+
push:
|
4 |
+
paths:
|
5 |
+
- '**.py'
|
6 |
+
jobs:
|
7 |
+
ruff:
|
8 |
+
runs-on: ubuntu-latest
|
9 |
+
steps:
|
10 |
+
- uses: actions/checkout@v4
|
11 |
+
- uses: chartboost/ruff-action@v1
|
.gitignore
ADDED
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transcibe.py
|
2 |
+
scraibe/*__pycache__
|
3 |
+
scraibe/app/*__pycache__
|
4 |
+
scraibe/.pyannotetoken
|
5 |
+
|
6 |
+
|
7 |
+
# Created by https://www.toptal.com/developers/gitignore/api/python,visualstudiocode,linux,windows
|
8 |
+
# Edit at https://www.toptal.com/developers/gitignore?templates=python,visualstudiocode,linux,windows
|
9 |
+
|
10 |
+
### Linux ###
|
11 |
+
*~
|
12 |
+
|
13 |
+
# temporary files which can be created if a process still has a handle open of a deleted file
|
14 |
+
.fuse_hidden*
|
15 |
+
|
16 |
+
# KDE directory preferences
|
17 |
+
.directory
|
18 |
+
|
19 |
+
# Linux trash folder which might appear on any partition or disk
|
20 |
+
.Trash-*
|
21 |
+
|
22 |
+
# .nfs files are created when an open file is removed but is still being accessed
|
23 |
+
.nfs*
|
24 |
+
|
25 |
+
### Python ###
|
26 |
+
# Byte-compiled / optimized / DLL files
|
27 |
+
__pycache__/
|
28 |
+
*.py[cod]
|
29 |
+
*$py.class
|
30 |
+
|
31 |
+
# C extensions
|
32 |
+
*.so
|
33 |
+
|
34 |
+
# Distribution / packaging
|
35 |
+
.Python
|
36 |
+
build/
|
37 |
+
develop-eggs/
|
38 |
+
dist/
|
39 |
+
downloads/
|
40 |
+
eggs/
|
41 |
+
.eggs/
|
42 |
+
lib/
|
43 |
+
lib64/
|
44 |
+
parts/
|
45 |
+
sdist/
|
46 |
+
var/
|
47 |
+
wheels/
|
48 |
+
share/python-wheels/
|
49 |
+
*.egg-info/
|
50 |
+
.installed.cfg
|
51 |
+
*.egg
|
52 |
+
MANIFEST
|
53 |
+
|
54 |
+
# PyInstaller
|
55 |
+
# Usually these files are written by a python script from a template
|
56 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
57 |
+
*.manifest
|
58 |
+
*.spec
|
59 |
+
|
60 |
+
# Installer logs
|
61 |
+
pip-log.txt
|
62 |
+
pip-delete-this-directory.txt
|
63 |
+
|
64 |
+
# Unit test / coverage reports
|
65 |
+
htmlcov/
|
66 |
+
.tox/
|
67 |
+
.nox/
|
68 |
+
.coverage
|
69 |
+
.coverage.*
|
70 |
+
.cache
|
71 |
+
nosetests.xml
|
72 |
+
coverage.xml
|
73 |
+
*.cover
|
74 |
+
*.py,cover
|
75 |
+
.hypothesis/
|
76 |
+
.pytest_cache/
|
77 |
+
cover/
|
78 |
+
|
79 |
+
# Translations
|
80 |
+
*.mo
|
81 |
+
*.pot
|
82 |
+
|
83 |
+
# Django stuff:
|
84 |
+
*.log
|
85 |
+
local_settings.py
|
86 |
+
db.sqlite3
|
87 |
+
db.sqlite3-journal
|
88 |
+
|
89 |
+
# Flask stuff:
|
90 |
+
instance/
|
91 |
+
.webassets-cache
|
92 |
+
|
93 |
+
# Scrapy stuff:
|
94 |
+
.scrapy
|
95 |
+
|
96 |
+
# Sphinx documentation
|
97 |
+
docs/_build/
|
98 |
+
|
99 |
+
# PyBuilder
|
100 |
+
.pybuilder/
|
101 |
+
target/
|
102 |
+
|
103 |
+
# Jupyter Notebook
|
104 |
+
.ipynb_checkpoints
|
105 |
+
|
106 |
+
# IPython
|
107 |
+
profile_default/
|
108 |
+
ipython_config.py
|
109 |
+
|
110 |
+
# pyenv
|
111 |
+
# For a library or package, you might want to ignore these files since the code is
|
112 |
+
# intended to run in multiple environments; otherwise, check them in:
|
113 |
+
# .python-version
|
114 |
+
|
115 |
+
# pipenv
|
116 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
117 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
118 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
119 |
+
# install all needed dependencies.
|
120 |
+
#Pipfile.lock
|
121 |
+
|
122 |
+
# poetry
|
123 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
124 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
125 |
+
# commonly ignored for libraries.
|
126 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
127 |
+
#poetry.lock
|
128 |
+
|
129 |
+
# pdm
|
130 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
131 |
+
#pdm.lock
|
132 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
133 |
+
# in version control.
|
134 |
+
# https://pdm.fming.dev/#use-with-ide
|
135 |
+
.pdm.toml
|
136 |
+
|
137 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
138 |
+
__pypackages__/
|
139 |
+
|
140 |
+
# Celery stuff
|
141 |
+
celerybeat-schedule
|
142 |
+
celerybeat.pid
|
143 |
+
|
144 |
+
# SageMath parsed files
|
145 |
+
*.sage.py
|
146 |
+
|
147 |
+
# Environments
|
148 |
+
.env
|
149 |
+
.venv
|
150 |
+
env/
|
151 |
+
venv/
|
152 |
+
ENV/
|
153 |
+
env.bak/
|
154 |
+
venv.bak/
|
155 |
+
|
156 |
+
# Spyder project settings
|
157 |
+
.spyderproject
|
158 |
+
.spyproject
|
159 |
+
|
160 |
+
# Rope project settings
|
161 |
+
.ropeproject
|
162 |
+
|
163 |
+
# mkdocs documentation
|
164 |
+
/site
|
165 |
+
|
166 |
+
# mypy
|
167 |
+
.mypy_cache/
|
168 |
+
.dmypy.json
|
169 |
+
dmypy.json
|
170 |
+
|
171 |
+
# Pyre type checker
|
172 |
+
.pyre/
|
173 |
+
|
174 |
+
# pytype static type analyzer
|
175 |
+
.pytype/
|
176 |
+
|
177 |
+
# Cython debug symbols
|
178 |
+
cython_debug/
|
179 |
+
|
180 |
+
# PyCharm
|
181 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
182 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
183 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
184 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
185 |
+
#.idea/
|
186 |
+
|
187 |
+
### Python Patch ###
|
188 |
+
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
189 |
+
poetry.toml
|
190 |
+
|
191 |
+
# ruff
|
192 |
+
.ruff_cache/
|
193 |
+
|
194 |
+
# LSP config files
|
195 |
+
pyrightconfig.json
|
196 |
+
|
197 |
+
### VisualStudioCode ###
|
198 |
+
.vscode/*
|
199 |
+
!.vscode/settings.json
|
200 |
+
!.vscode/tasks.json
|
201 |
+
!.vscode/launch.json
|
202 |
+
!.vscode/extensions.json
|
203 |
+
!.vscode/*.code-snippets
|
204 |
+
|
205 |
+
# Local History for Visual Studio Code
|
206 |
+
.history/
|
207 |
+
|
208 |
+
# Built Visual Studio Code Extensions
|
209 |
+
*.vsix
|
210 |
+
|
211 |
+
### VisualStudioCode Patch ###
|
212 |
+
# Ignore all local history of files
|
213 |
+
.history
|
214 |
+
.ionide
|
215 |
+
|
216 |
+
### Windows ###
|
217 |
+
# Windows thumbnail cache files
|
218 |
+
Thumbs.db
|
219 |
+
Thumbs.db:encryptable
|
220 |
+
ehthumbs.db
|
221 |
+
ehthumbs_vista.db
|
222 |
+
|
223 |
+
# Dump file
|
224 |
+
*.stackdump
|
225 |
+
|
226 |
+
# Folder config file
|
227 |
+
[Dd]esktop.ini
|
228 |
+
|
229 |
+
# Recycle Bin used on file shares
|
230 |
+
$RECYCLE.BIN/
|
231 |
+
|
232 |
+
# Windows Installer files
|
233 |
+
*.cab
|
234 |
+
*.msi
|
235 |
+
*.msix
|
236 |
+
*.msm
|
237 |
+
*.msp
|
238 |
+
|
239 |
+
# Windows shortcuts
|
240 |
+
*.lnk
|
241 |
+
|
242 |
+
# End of https://www.toptal.com/developers/gitignore/api/python,visualstudiocode,linux,windows
|
CHANGELOG.md
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Changelog
|
2 |
+
|
3 |
+
All notable changes to this project will be documented in this file.
|
4 |
+
|
5 |
+
## [0.2.0] - 2024-05-28
|
6 |
+
|
7 |
+
### Added
|
8 |
+
|
9 |
+
- **Python Usage Section**: Detailed instructions on how to use ScrAIbe with Python, including examples for Whisper models, WhisperX, and keyword arguments.
|
10 |
+
- **Command-line Usage Section**: Enhanced instructions for using ScrAIbe via the command-line interface, including examples and key options.
|
11 |
+
- **Documentation Section**: Expanded the documentation section with highlights on installation guides, usage examples, API reference, troubleshooting tips, and advanced configuration.
|
12 |
+
- **Getting Started Section**: Added detailed prerequisites and installation instructions for both stable and development versions of ScrAIbe.
|
13 |
+
- **WhisperX Support**: Added support for the WhisperX backend.
|
14 |
+
|
15 |
+
### Changed
|
16 |
+
|
17 |
+
- **Model Customization**: Clarified the use of various keywords to customize Whisper models, Pyannote diarization models, and WhisperX.
|
18 |
+
- **Example Enhancements**: Improved examples to illustrate the usage of different features and options in ScrAIbe.
|
19 |
+
- **Formatting and Clarity**: Improved formatting and clarity across all sections to enhance readability and user experience.
|
20 |
+
- **Backend Robustness**: Enhanced the backend to be more robust, removing the need for a HuggingFace token for basic usage.
|
21 |
+
- **CLI**: to Work without Gradio
|
22 |
+
|
23 |
+
### Removed
|
24 |
+
|
25 |
+
- **Docker Build**: Removed Docker build support.
|
26 |
+
- **Gradio App**: Removed the Gradio App integration.
|
27 |
+
|
28 |
+
Both the Docker Build and the Gradio App are now Available under [ScrAIbe-WebUI](https://github.com/JSchmie/ScrAIbe-WebUI)
|
29 |
+
|
30 |
+
### Documentation
|
31 |
+
|
32 |
+
- **Documentation Page Link**: Updated the documentation section with a direct link to the [ScrAIbe documentation page](https://jschmie.github.io/ScrAIbe/).
|
33 |
+
|
34 |
+
**Note**: This changelog might be incomplete, but we promise to improve it in the future. Thank you for your understanding and support.
|
CONTRIBUTING.md
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to ScrAIbe
|
2 |
+
|
3 |
+
Thank you for your interest in contributing to ScrAIbe! We appreciate your efforts to improve the project. Before making any changes, please discuss them with the project maintainers via an issue, email, or any other method.
|
4 |
+
|
5 |
+
Please note that we have a code of conduct, and we ask you to adhere to it in all your interactions with the project.
|
6 |
+
|
7 |
+
## Pull Request Process
|
8 |
+
|
9 |
+
1. **Dependency Management**: Ensure any install or build dependencies are removed before the end of the layer when doing a build.
|
10 |
+
2. **Documentation Updates**: Update the `README.md` with details of changes to the interface, including new environment variables, exposed ports, useful file locations, and container parameters.
|
11 |
+
3. **Versioning**: Increase the version numbers in any example files and the `README.md` to the new version that this Pull Request would represent. We use the [SemVer](http://semver.org/) versioning scheme.
|
12 |
+
4. **Review and Merge**: You may merge the Pull Request once you have the sign-off of two other developers. If you do not have permission to merge, request a second reviewer to merge it for you.
|
13 |
+
|
14 |
+
## Code of Conduct
|
15 |
+
|
16 |
+
### Our Pledge
|
17 |
+
|
18 |
+
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
19 |
+
|
20 |
+
### Our Standards
|
21 |
+
|
22 |
+
Examples of behavior that contributes to creating a positive environment include:
|
23 |
+
|
24 |
+
* Using welcoming and inclusive language
|
25 |
+
* Being respectful of differing viewpoints and experiences
|
26 |
+
* Gracefully accepting constructive criticism
|
27 |
+
* Focusing on what is best for the community
|
28 |
+
* Showing empathy towards other community members
|
29 |
+
|
30 |
+
Examples of unacceptable behavior by participants include:
|
31 |
+
|
32 |
+
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
33 |
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
34 |
+
* Public or private harassment
|
35 |
+
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
36 |
+
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
37 |
+
|
38 |
+
### Our Responsibilities
|
39 |
+
|
40 |
+
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
41 |
+
|
42 |
+
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
43 |
+
|
44 |
+
### Scope
|
45 |
+
|
46 |
+
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
47 |
+
|
48 |
+
### Enforcement
|
49 |
+
|
50 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
51 |
+
|
52 |
+
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
53 |
+
|
54 |
+
### Attribution
|
55 |
+
|
56 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version].
|
57 |
+
|
58 |
+
[homepage]: http://contributor-covenant.org
|
59 |
+
[version]: http://contributor-covenant.org/version/1/4/
|
Dockerfile
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#pytorch Image
|
2 |
+
FROM pytorch/pytorch:2.3.1-cuda12.1-cudnn8-runtime
|
3 |
+
|
4 |
+
# Labels
|
5 |
+
|
6 |
+
LABEL maintainer="Jacob Schmieder"
|
7 |
+
LABEL email="[email protected]"
|
8 |
+
LABEL version="0.1.1.dev"
|
9 |
+
LABEL description="Scraibe is a tool for automatic speech recognition and speaker diarization. \
|
10 |
+
It is based on the Hugging Face Transformers library and the Pyannote library. \
|
11 |
+
It is designed to be used with the Whisper model, a lightweight model for automatic \
|
12 |
+
speech recognition and speaker diarization."
|
13 |
+
LABEL url="https://github.com/JSchmie/ScrAIbe"
|
14 |
+
|
15 |
+
# Set up a new user named "hyathi" with user ID 1001
|
16 |
+
RUN useradd -m -u 1000 hyathi
|
17 |
+
# Switch to the new user
|
18 |
+
|
19 |
+
USER hyathi
|
20 |
+
# Set home to the user's home directory
|
21 |
+
ENV HOME=/home/hyathi \
|
22 |
+
PATH=/home/hyathi/.local/bin:$PATH
|
23 |
+
# Set the working directory to the user's home directory
|
24 |
+
|
25 |
+
# Install dependencies
|
26 |
+
WORKDIR $HOME/app
|
27 |
+
|
28 |
+
|
29 |
+
#Enviorment dependencies
|
30 |
+
ENV TRANSFORMERS_CACHE=/app/models
|
31 |
+
ENV HF_HOME=/app/models
|
32 |
+
ENV AUTOT_CACHE=/app/models
|
33 |
+
ENV PYANNOTE_CACHE=/app/models/pyannote
|
34 |
+
#Copy all necessary files
|
35 |
+
COPY requirements.txt /app/requirements.txt
|
36 |
+
COPY README.md /app/README.md
|
37 |
+
COPY scraibe /app/scraibe
|
38 |
+
|
39 |
+
#Installing all necessary dependencies and running the application with a personalised Hugging-Face-Token
|
40 |
+
RUN apt update -y && apt upgrade -y && \
|
41 |
+
apt install -y libsm6 libxrender1 libfontconfig1 && \
|
42 |
+
apt clean && \
|
43 |
+
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
44 |
+
|
45 |
+
RUN conda update --all && \
|
46 |
+
# conda install -y pip ffmpeg && \
|
47 |
+
conda install -c conda-forge libsndfile && \
|
48 |
+
conda clean --all -y
|
49 |
+
# RUN pip install torchaudio==0.11.0+cu113 -f https://download.pytorch.org/whl/torch_stable.html
|
50 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
51 |
+
|
52 |
+
# Expose port
|
53 |
+
EXPOSE 7860
|
54 |
+
# Run the application
|
55 |
+
|
56 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--reload"]
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
Makefile
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Minimal makefile for Sphinx documentation
|
2 |
+
#
|
3 |
+
|
4 |
+
# You can set these variables from the command line, and also
|
5 |
+
# from the environment for the first two.
|
6 |
+
SPHINXOPTS ?=
|
7 |
+
SPHINXBUILD ?= sphinx-build
|
8 |
+
SOURCEDIR = source
|
9 |
+
BUILDDIR = build
|
10 |
+
|
11 |
+
# Put it first so that "make" without argument is like "make help".
|
12 |
+
help:
|
13 |
+
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
14 |
+
|
15 |
+
.PHONY: help Makefile
|
16 |
+
|
17 |
+
# Catch-all target: route all unknown targets to Sphinx using the new
|
18 |
+
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
19 |
+
%: Makefile
|
20 |
+
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
app.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from typing import List
|
4 |
+
import os
|
5 |
+
import requests
|
6 |
+
from tempfile import NamedTemporaryFile
|
7 |
+
from scraibe import Scraibe
|
8 |
+
|
9 |
+
app = FastAPI()
|
10 |
+
|
11 |
+
# Initialize the Scraibe model with the specified parameters
|
12 |
+
WHISPER_MODEL_NAME = "large-v3"
|
13 |
+
WHISPER_TYPE = "whisper"
|
14 |
+
|
15 |
+
scraibe_model = Scraibe(
|
16 |
+
whisper_model=WHISPER_MODEL_NAME,
|
17 |
+
whisper_type=WHISPER_TYPE,
|
18 |
+
)
|
19 |
+
|
20 |
+
class TranscriptionRequest(BaseModel):
|
21 |
+
audio_links: List[str]
|
22 |
+
|
23 |
+
|
24 |
+
def download_audio_from_s3(s3_url: str) -> str:
|
25 |
+
"""
|
26 |
+
Download an audio file from an S3 URL and save it locally.
|
27 |
+
|
28 |
+
Args:
|
29 |
+
s3_url (str): The S3 URL of the audio file.
|
30 |
+
|
31 |
+
Returns:
|
32 |
+
str: Path to the downloaded audio file.
|
33 |
+
"""
|
34 |
+
try:
|
35 |
+
response = requests.get(s3_url, stream=True)
|
36 |
+
response.raise_for_status()
|
37 |
+
|
38 |
+
# Create a temporary file to save the audio
|
39 |
+
temp_file = NamedTemporaryFile(delete=False, suffix=".wav")
|
40 |
+
with open(temp_file.name, "wb") as f:
|
41 |
+
for chunk in response.iter_content(chunk_size=8192):
|
42 |
+
f.write(chunk)
|
43 |
+
print(f"Downloaded audio file to {temp_file.name}")
|
44 |
+
|
45 |
+
return temp_file.name
|
46 |
+
|
47 |
+
except requests.exceptions.RequestException as e:
|
48 |
+
raise HTTPException(status_code=400, detail=f"Failed to download file from S3: {str(e)}")
|
49 |
+
|
50 |
+
@app.post("/transcribe")
|
51 |
+
async def transcribe_audio(request: TranscriptionRequest):
|
52 |
+
"""
|
53 |
+
Endpoint to transcribe audio files from S3 links.
|
54 |
+
|
55 |
+
Args:
|
56 |
+
request (TranscriptionRequest): Input data containing S3 audio links and parameters.
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
dict: Transcription results.
|
60 |
+
"""
|
61 |
+
results = {}
|
62 |
+
|
63 |
+
try:
|
64 |
+
for s3_link in request.audio_links:
|
65 |
+
# Download the audio file from the S3 link
|
66 |
+
audio_path = download_audio_from_s3(s3_link)
|
67 |
+
|
68 |
+
# Perform the transcription
|
69 |
+
transcription = scraibe_model.autotranscribe(
|
70 |
+
audio_path,
|
71 |
+
)
|
72 |
+
|
73 |
+
# Collect the result
|
74 |
+
results[s3_link] = transcription
|
75 |
+
|
76 |
+
# Clean up the downloaded file
|
77 |
+
os.remove(audio_path)
|
78 |
+
|
79 |
+
return results
|
80 |
+
|
81 |
+
except Exception as e:
|
82 |
+
raise HTTPException(status_code=500, detail=str(e))
|
pyproject.toml
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[build-system]
|
2 |
+
requires = ["poetry-core>=1.8.0", "poetry-dynamic-versioning>=1.0.0,<2.0.0"]
|
3 |
+
build-backend = "poetry_dynamic_versioning.backend"
|
4 |
+
|
5 |
+
[tool.poetry]
|
6 |
+
name = "scraibe"
|
7 |
+
version = "0.0.0"
|
8 |
+
description = "Transcription tool for audio files based on Whisper and Pyannote"
|
9 |
+
authors = ["Schmieder, Jacob <[email protected]>"]
|
10 |
+
license = "GPL-3.0-or-later"
|
11 |
+
readme = ["README.md", "LICENSE"]
|
12 |
+
repository = "https://github.com/JSchmie/ScAIbe"
|
13 |
+
documentation = "https://jschmie.github.io/ScrAIbe/"
|
14 |
+
keywords = ["transcription", "audio", "whisper", "pyannote", "speech-to-text", "speech-recognition"]
|
15 |
+
classifiers = [
|
16 |
+
'Development Status :: 4 - Beta',
|
17 |
+
'Intended Audience :: Developers',
|
18 |
+
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
|
19 |
+
'Programming Language :: Python :: 3.8',
|
20 |
+
'Programming Language :: Python :: 3.9',
|
21 |
+
'Programming Language :: Python :: 3.10',
|
22 |
+
'Programming Language :: Python :: 3.11',
|
23 |
+
'Environment :: GPU :: NVIDIA CUDA :: 12 :: 12.1',
|
24 |
+
'Topic :: Scientific/Engineering :: Artificial Intelligence'
|
25 |
+
]
|
26 |
+
packages = [{include = "scraibe"}]
|
27 |
+
exclude =[
|
28 |
+
"__pycache__",
|
29 |
+
"*.pyc",
|
30 |
+
"test"
|
31 |
+
]
|
32 |
+
[tool.poetry.dependencies]
|
33 |
+
python = "^3.9"
|
34 |
+
tqdm = "^4.66.5"
|
35 |
+
numpy = "^1.26.4"
|
36 |
+
openai-whisper = ">=20231117,<20240931"
|
37 |
+
faster-whisper = "^1.0.3"
|
38 |
+
"pyannote.audio" = "^3.3.1"
|
39 |
+
torch = "^2.1.2"
|
40 |
+
|
41 |
+
[tool.poetry.group.dev.dependencies]
|
42 |
+
pytest = "^8.1.1"
|
43 |
+
|
44 |
+
[tool.poetry-dynamic-versioning]
|
45 |
+
enable = true
|
46 |
+
vcs = "git"
|
47 |
+
strict = true
|
48 |
+
format-jinja = """
|
49 |
+
{%- if distance == 0 -%}
|
50 |
+
{{ serialize_pep440(base) }}
|
51 |
+
{%- elif branch == 'develop' -%}
|
52 |
+
{{ serialize_pep440(bump_version(base), dev = distance) }}
|
53 |
+
{%- else -%}
|
54 |
+
{{ serialize_pep440(bump_version(base), dev=distance, metadata=[commit]) }}
|
55 |
+
{%- endif -%}
|
56 |
+
"""
|
57 |
+
|
58 |
+
[tool.poetry.group.docs.dependencies]
|
59 |
+
sphinx = "^7.3.7"
|
60 |
+
sphinx-rtd-theme = ">=2,<4"
|
61 |
+
markdown-it-py = {version = "~3.0.0", extras = ["plugins"]}
|
62 |
+
myst-parser = "^3.0.1"
|
63 |
+
mdit-py-plugins = "^0.4.1"
|
64 |
+
|
65 |
+
[tool.poetry.scripts]
|
66 |
+
scraibe = "scraibe.cli:cli"
|
67 |
+
|
68 |
+
[tool.poetry.extras]
|
69 |
+
app = ["scraibe-webui"]
|
70 |
+
|
71 |
+
[tool.ruff.lint.extend-per-file-ignores]
|
72 |
+
"__init__.py" = ["E402","F403",'F401']
|
73 |
+
"scraibe/misc.py" = ["E722"]
|
requirements.txt
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
tqdm>=4.66.5
|
2 |
+
numpy>=1.26.4
|
3 |
+
|
4 |
+
openai-whisper==20231117
|
5 |
+
faster-whisper~=1.0.3
|
6 |
+
|
7 |
+
pyannote.audio~=3.3.1
|
8 |
+
pyannote.core~=5.0.0
|
9 |
+
pyannote.database~=5.0.1
|
10 |
+
pyannote.metrics~=3.2.1
|
11 |
+
pyannote.pipeline~=3.0.1
|
12 |
+
|
13 |
+
torchaudio>=2.1.2
|
14 |
+
|
15 |
+
fastapi
|
16 |
+
uvicorn
|
17 |
+
|
scraibe/__init__.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .autotranscript import *
|
2 |
+
from .transcriber import *
|
3 |
+
from .audio import *
|
4 |
+
from .transcript_exporter import *
|
5 |
+
from .diarisation import *
|
6 |
+
|
7 |
+
from .misc import *
|
8 |
+
|
9 |
+
from .cli import *
|
10 |
+
|
11 |
+
from ._version import __version__
|
scraibe/_version.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
__version__ = "0.0.0"
|
scraibe/audio.py
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Audio Processor Module
|
3 |
+
=======================
|
4 |
+
|
5 |
+
This module provides the AudioProcessor class, utilizing PyTorchaudio for handling audio files.
|
6 |
+
It includes functionalities to load, cut, and manage audio waveforms, offering efficient and
|
7 |
+
flexible audio processing.
|
8 |
+
|
9 |
+
Available Classes:
|
10 |
+
- AudioProcessor: Processes audio waveforms and provides methods for loading,
|
11 |
+
cutting, and handling audio.
|
12 |
+
|
13 |
+
Usage:
|
14 |
+
from .audio_import AudioProcessor
|
15 |
+
|
16 |
+
processor = AudioProcessor.from_file("path/to/audiofile.wav")
|
17 |
+
cut_waveform = processor.cut(start=1.0, end=5.0)
|
18 |
+
|
19 |
+
Constants:
|
20 |
+
- SAMPLE_RATE (int): Default sample rate for processing.
|
21 |
+
- NORMALIZATION_FACTOR (float): Normalization factor for audio waveform.
|
22 |
+
"""
|
23 |
+
|
24 |
+
from subprocess import CalledProcessError, run
|
25 |
+
import numpy as np
|
26 |
+
import torch
|
27 |
+
|
28 |
+
SAMPLE_RATE = 16000
|
29 |
+
NORMALIZATION_FACTOR = 32768.0
|
30 |
+
|
31 |
+
|
32 |
+
class AudioProcessor:
|
33 |
+
"""
|
34 |
+
Audio Processor class that leverages PyTorchaudio to provide functionalities
|
35 |
+
for loading, cutting, and handling audio waveforms.
|
36 |
+
|
37 |
+
Attributes:
|
38 |
+
waveform: torch.Tensor
|
39 |
+
The audio waveform tensor.
|
40 |
+
sr: int
|
41 |
+
The sample rate of the audio.
|
42 |
+
"""
|
43 |
+
|
44 |
+
def __init__(self, waveform: torch.Tensor,
|
45 |
+
sr: int = SAMPLE_RATE) -> None:
|
46 |
+
"""
|
47 |
+
Initialize the AudioProcessor object.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
waveform (torch.Tensor): The audio waveform tensor.
|
51 |
+
sr (int, optional): The sample rate of the audio. Defaults to SAMPLE_RATE.
|
52 |
+
|
53 |
+
Raises:
|
54 |
+
ValueError: If the provided sample rate is not of type int.
|
55 |
+
"""
|
56 |
+
|
57 |
+
self.waveform = waveform
|
58 |
+
self.sr = sr
|
59 |
+
|
60 |
+
if not isinstance(self.sr, int):
|
61 |
+
raise ValueError("Sample rate should be a single value of type int,"
|
62 |
+
f"not {len(self.sr)} and type {type(self.sr)}")
|
63 |
+
|
64 |
+
@classmethod
|
65 |
+
def from_file(cls, file: str, *args, **kwargs) -> 'AudioProcessor':
|
66 |
+
"""
|
67 |
+
Create an AudioProcessor instance from an audio file.
|
68 |
+
|
69 |
+
Args:
|
70 |
+
file (str): The audio file path.
|
71 |
+
|
72 |
+
Returns:
|
73 |
+
AudioProcessor: An instance of the AudioProcessor class containing the loaded audio.
|
74 |
+
"""
|
75 |
+
|
76 |
+
audio, sr = cls.load_audio(file, *args, **kwargs)
|
77 |
+
|
78 |
+
audio = torch.from_numpy(audio)
|
79 |
+
|
80 |
+
return cls(audio, sr)
|
81 |
+
|
82 |
+
def cut(self, start: float, end: float) -> torch.Tensor:
|
83 |
+
"""
|
84 |
+
Cut a segment from the audio waveform between the specified start and end times.
|
85 |
+
|
86 |
+
Args:
|
87 |
+
start (float): Start time in seconds.
|
88 |
+
end (float): End time in seconds.
|
89 |
+
|
90 |
+
Returns:
|
91 |
+
torch.Tensor: The cut waveform segment.
|
92 |
+
"""
|
93 |
+
|
94 |
+
start = int(start * self.sr)
|
95 |
+
if (isinstance(end, float) or isinstance(end, int)) and isinstance(self.sr, int):
|
96 |
+
end = int(np.ceil(end * self.sr))
|
97 |
+
else:
|
98 |
+
end = int(torch.ceil(end * self.sr))
|
99 |
+
return self.waveform[start:end]
|
100 |
+
|
101 |
+
@staticmethod
|
102 |
+
def load_audio(file: str, sr: int = SAMPLE_RATE):
|
103 |
+
"""
|
104 |
+
Open an audio file and read it as a mono waveform, resampling if necessary.
|
105 |
+
This method ensures compatibility with pyannote.audio
|
106 |
+
and requires the ffmpeg CLI in PATH.
|
107 |
+
|
108 |
+
Args:
|
109 |
+
file (str): The audio file to open.
|
110 |
+
sr (int, optional): The desired sample rate. Defaults to SAMPLE_RATE.
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
tuple: A NumPy array containing the audio waveform in float32 dtype
|
114 |
+
and the sample rate.
|
115 |
+
|
116 |
+
Raises:
|
117 |
+
RuntimeError: If failed to load audio.
|
118 |
+
"""
|
119 |
+
# This launches a subprocess to decode audio while down-mixing
|
120 |
+
# and resampling as necessary. Requires the ffmpeg CLI in PATH.
|
121 |
+
# fmt: off
|
122 |
+
cmd = [
|
123 |
+
"ffmpeg",
|
124 |
+
"-nostdin",
|
125 |
+
"-threads", "0",
|
126 |
+
"-i", file,
|
127 |
+
"-f", "s16le",
|
128 |
+
"-ac", "1",
|
129 |
+
"-acodec", "pcm_s16le",
|
130 |
+
"-ar", str(sr),
|
131 |
+
"-"
|
132 |
+
]
|
133 |
+
# fmt: on
|
134 |
+
try:
|
135 |
+
out = run(cmd, capture_output=True, check=True).stdout
|
136 |
+
except CalledProcessError as e:
|
137 |
+
raise RuntimeError(
|
138 |
+
f"Failed to load audio: {e.stderr.decode()}") from e
|
139 |
+
|
140 |
+
out = np.frombuffer(out, np.int16).flatten().astype(
|
141 |
+
np.float32) / NORMALIZATION_FACTOR
|
142 |
+
|
143 |
+
return out, sr
|
144 |
+
|
145 |
+
def __repr__(self) -> str:
|
146 |
+
return f'TorchAudioProcessor(waveform={len(self.waveform)}, sr={int(self.sr)})'
|
scraibe/autotranscript.py
ADDED
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Scraibe Class
|
3 |
+
--------------------
|
4 |
+
|
5 |
+
This class serves as the core of the transcription system, responsible for handling
|
6 |
+
transcription and diarization of audio files. It leverages pretrained models for
|
7 |
+
speech-to-text (such as Whisper) and speaker diarization (such as pyannote.audio),
|
8 |
+
providing an accessible interface for audio processing tasks such as transcription,
|
9 |
+
speaker separation, and timestamping.
|
10 |
+
|
11 |
+
By encapsulating the complexities of underlying models, it allows for straightforward
|
12 |
+
integration into various applications, ranging from transcription services to voice assistants.
|
13 |
+
|
14 |
+
Available Classes:
|
15 |
+
- Scraibe: Main class for performing transcription and diarization.
|
16 |
+
Includes methods for loading models, processing audio files,
|
17 |
+
and formatting the transcription output.
|
18 |
+
|
19 |
+
Usage:
|
20 |
+
from scraibe import Scraibe
|
21 |
+
|
22 |
+
model = Scraibe()
|
23 |
+
transcript = model.autotranscribe("path/to/audiofile.wav")
|
24 |
+
"""
|
25 |
+
|
26 |
+
# Standard Library Imports
|
27 |
+
import os
|
28 |
+
from glob import iglob
|
29 |
+
from subprocess import run
|
30 |
+
from typing import TypeVar, Union
|
31 |
+
from warnings import warn
|
32 |
+
|
33 |
+
# Third-Party Imports
|
34 |
+
import torch
|
35 |
+
from numpy import ndarray
|
36 |
+
from tqdm import trange
|
37 |
+
|
38 |
+
# Application-Specific Imports
|
39 |
+
from .audio import AudioProcessor
|
40 |
+
from .diarisation import Diariser
|
41 |
+
from .transcriber import Transcriber, load_transcriber, whisper
|
42 |
+
from .transcript_exporter import Transcript
|
43 |
+
from .misc import SCRAIBE_TORCH_DEVICE
|
44 |
+
|
45 |
+
|
46 |
+
DiarisationType = TypeVar('DiarisationType')
|
47 |
+
|
48 |
+
|
49 |
+
class Scraibe:
|
50 |
+
"""
|
51 |
+
Scraibe is a class responsible for managing the transcription and diarization of audio files.
|
52 |
+
It serves as the core of the transcription system, incorporating pretrained models
|
53 |
+
for speech-to-text (such as Whisper) and speaker diarization (such as pyannote.audio),
|
54 |
+
allowing for comprehensive audio processing.
|
55 |
+
|
56 |
+
Attributes:
|
57 |
+
transcriber (Transcriber): The transcriber object to handle transcription.
|
58 |
+
diariser (Diariser): The diariser object to handle diarization.
|
59 |
+
|
60 |
+
Methods:
|
61 |
+
__init__: Initializes the Scraibe class with appropriate models.
|
62 |
+
transcribe: Transcribes an audio file using the whisper model and pyannote diarization model.
|
63 |
+
remove_audio_file: Removes the original audio file to avoid disk space issues or ensure data privacy.
|
64 |
+
get_audio_file: Gets an audio file as an AudioProcessor object.
|
65 |
+
"""
|
66 |
+
|
67 |
+
def __init__(self,
|
68 |
+
whisper_model: Union[bool, str, whisper] = None,
|
69 |
+
whisper_type: str = "whisper",
|
70 |
+
dia_model: Union[bool, str, DiarisationType] = None,
|
71 |
+
**kwargs) -> None:
|
72 |
+
"""Initializes the Scraibe class.
|
73 |
+
|
74 |
+
Args:
|
75 |
+
whisper_model (Union[bool, str, whisper], optional):
|
76 |
+
Path to whisper model or whisper model itself.
|
77 |
+
whisper_type (str):
|
78 |
+
Type of whisper model to load. "whisper" or "faster-whisper".
|
79 |
+
diarisation_model (Union[bool, str, DiarisationType], optional):
|
80 |
+
Path to pyannote diarization model or model itself.
|
81 |
+
**kwargs: Additional keyword arguments for whisper
|
82 |
+
and pyannote diarization models.
|
83 |
+
e.g.:
|
84 |
+
|
85 |
+
- verbose: If True, the class will print additional information.
|
86 |
+
- save_kwargs: If True, the keyword arguments will be saved
|
87 |
+
for autotranscribe. So you can unload the class and reload it again.
|
88 |
+
"""
|
89 |
+
|
90 |
+
if whisper_model is None:
|
91 |
+
self.transcriber = load_transcriber(
|
92 |
+
"large-v3", whisper_type, **kwargs)
|
93 |
+
elif isinstance(whisper_model, str):
|
94 |
+
self.transcriber = load_transcriber(
|
95 |
+
whisper_model, whisper_type, **kwargs)
|
96 |
+
else:
|
97 |
+
self.transcriber = whisper_model
|
98 |
+
|
99 |
+
if dia_model is None:
|
100 |
+
self.diariser = Diariser.load_model(**kwargs)
|
101 |
+
elif isinstance(dia_model, str):
|
102 |
+
self.diariser = Diariser.load_model(dia_model, **kwargs)
|
103 |
+
else:
|
104 |
+
self.diariser: Diariser = dia_model
|
105 |
+
|
106 |
+
if kwargs.get("verbose"):
|
107 |
+
print("Scraibe initialized all models successfully loaded.")
|
108 |
+
self.verbose = True
|
109 |
+
else:
|
110 |
+
self.verbose = False
|
111 |
+
|
112 |
+
# Save kwargs for autotranscribe if you want to unload the class and load it again.
|
113 |
+
if kwargs.get('save_setup'):
|
114 |
+
self.params = dict(whisper_model=whisper_model,
|
115 |
+
dia_model=dia_model,
|
116 |
+
**kwargs)
|
117 |
+
else:
|
118 |
+
self.params = {}
|
119 |
+
|
120 |
+
self.device = kwargs.get(
|
121 |
+
"device", SCRAIBE_TORCH_DEVICE)
|
122 |
+
|
123 |
+
def autotranscribe(self, audio_file: Union[str, torch.Tensor, ndarray],
|
124 |
+
remove_original: bool = False,
|
125 |
+
**kwargs) -> Transcript:
|
126 |
+
"""
|
127 |
+
Transcribes an audio file using the whisper model and pyannote diarization model.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
audio_file (Union[str, torch.Tensor, ndarray]):
|
131 |
+
Path to audio file or a tensor representing the audio.
|
132 |
+
remove_original (bool, optional): If True, the original audio file will
|
133 |
+
be removed after transcription.
|
134 |
+
*args: Additional positional arguments for diarization and transcription.
|
135 |
+
**kwargs: Additional keyword arguments for diarization and transcription.
|
136 |
+
|
137 |
+
Returns:
|
138 |
+
Transcript: A Transcript object containing the transcription,
|
139 |
+
which can be exported to different formats.
|
140 |
+
"""
|
141 |
+
if kwargs.get("verbose"):
|
142 |
+
self.verbose = kwargs.get("verbose")
|
143 |
+
# Get audio file as an AudioProcessor object
|
144 |
+
audio_file: AudioProcessor = self.get_audio_file(audio_file)
|
145 |
+
|
146 |
+
# Prepare waveform and sample rate for diarization
|
147 |
+
dia_audio = {
|
148 |
+
"waveform": audio_file.waveform.reshape(1, len(audio_file.waveform)).to(self.device),
|
149 |
+
"sample_rate": audio_file.sr
|
150 |
+
}
|
151 |
+
|
152 |
+
if self.verbose:
|
153 |
+
print("Starting diarisation.")
|
154 |
+
|
155 |
+
diarisation = self.diariser.diarization(dia_audio, **kwargs)
|
156 |
+
|
157 |
+
if not diarisation["segments"]:
|
158 |
+
print("No segments found. Try to run transcription without diarisation.")
|
159 |
+
|
160 |
+
transcript = self.transcriber.transcribe(
|
161 |
+
audio_file.waveform, **kwargs)
|
162 |
+
|
163 |
+
final_transcript = {0: {"speakers": 'SPEAKER_01',
|
164 |
+
"segments": [0, len(audio_file.waveform)],
|
165 |
+
"text": transcript}}
|
166 |
+
|
167 |
+
return Transcript(final_transcript)
|
168 |
+
|
169 |
+
if self.verbose:
|
170 |
+
print("Diarisation finished. Starting transcription.")
|
171 |
+
|
172 |
+
|
173 |
+
# Transcribe each segment and store the results
|
174 |
+
final_transcript = dict()
|
175 |
+
|
176 |
+
for i in trange(len(diarisation["segments"]), desc="Transcribing", disable=not self.verbose):
|
177 |
+
|
178 |
+
seg = diarisation["segments"][i]
|
179 |
+
|
180 |
+
audio = audio_file.cut(seg[0], seg[1])
|
181 |
+
|
182 |
+
transcript = self.transcriber.transcribe(audio, **kwargs)
|
183 |
+
|
184 |
+
final_transcript[i] = {"speakers": diarisation["speakers"][i],
|
185 |
+
"segments": seg,
|
186 |
+
"text": transcript}
|
187 |
+
|
188 |
+
# Remove original file if needed
|
189 |
+
if remove_original:
|
190 |
+
if kwargs.get("shred") is True:
|
191 |
+
self.remove_audio_file(audio_file, shred=True)
|
192 |
+
else:
|
193 |
+
self.remove_audio_file(audio_file, shred=False)
|
194 |
+
|
195 |
+
return Transcript(final_transcript)
|
196 |
+
|
197 |
+
def diarization(self, audio_file: Union[str, torch.Tensor, ndarray],
|
198 |
+
**kwargs) -> dict:
|
199 |
+
"""
|
200 |
+
Perform diarization on an audio file using the pyannote diarization model.
|
201 |
+
|
202 |
+
Args:
|
203 |
+
audio_file (Union[str, torch.Tensor, ndarray]):
|
204 |
+
The audio source which can either be a path to the audio file or a tensor representation.
|
205 |
+
**kwargs:
|
206 |
+
Additional keyword arguments for diarization.
|
207 |
+
|
208 |
+
Returns:
|
209 |
+
dict:
|
210 |
+
A dictionary containing the results of the diarization process.
|
211 |
+
"""
|
212 |
+
|
213 |
+
# Get audio file as an AudioProcessor object
|
214 |
+
audio_file: AudioProcessor = self.get_audio_file(audio_file)
|
215 |
+
|
216 |
+
# Prepare waveform and sample rate for diarization
|
217 |
+
dia_audio = {
|
218 |
+
"waveform": audio_file.waveform.reshape(1, len(audio_file.waveform)).to(self.device),
|
219 |
+
"sample_rate": audio_file.sr
|
220 |
+
}
|
221 |
+
|
222 |
+
print("Starting diarisation.")
|
223 |
+
|
224 |
+
diarisation = self.diariser.diarization(dia_audio, **kwargs)
|
225 |
+
|
226 |
+
return diarisation
|
227 |
+
|
228 |
+
def transcribe(self, audio_file: Union[str, torch.Tensor, ndarray],
|
229 |
+
**kwargs):
|
230 |
+
"""
|
231 |
+
Transcribe the provided audio file.
|
232 |
+
|
233 |
+
Args:
|
234 |
+
audio_file (Union[str, torch.Tensor, ndarray]):
|
235 |
+
The audio source, which can either be a path or a tensor representation.
|
236 |
+
**kwargs:
|
237 |
+
Additional keyword arguments for transcription.
|
238 |
+
|
239 |
+
Returns:
|
240 |
+
str:
|
241 |
+
The transcribed text from the audio source.
|
242 |
+
"""
|
243 |
+
audio_file: AudioProcessor = self.get_audio_file(audio_file)
|
244 |
+
|
245 |
+
return self.transcriber.transcribe(audio_file.waveform, **kwargs)
|
246 |
+
|
247 |
+
def update_transcriber(self, whisper_model: Union[str, whisper], **kwargs) -> None:
|
248 |
+
"""
|
249 |
+
Update the transcriber model.
|
250 |
+
|
251 |
+
Args:
|
252 |
+
whisper_model (Union[str, whisper]):
|
253 |
+
The new whisper model to use for transcription.
|
254 |
+
**kwargs:
|
255 |
+
Additional keyword arguments for the transcriber model.
|
256 |
+
|
257 |
+
Returns:
|
258 |
+
None
|
259 |
+
"""
|
260 |
+
_old_model = self.transcriber.model_name
|
261 |
+
|
262 |
+
if isinstance(whisper_model, str):
|
263 |
+
self.transcriber = load_transcriber(whisper_model, **kwargs)
|
264 |
+
elif isinstance(whisper_model, Transcriber):
|
265 |
+
self.transcriber = whisper_model
|
266 |
+
else:
|
267 |
+
warn(
|
268 |
+
f"Invalid model type. Please provide a valid model. Fallback to old {_old_model} Model.", RuntimeWarning)
|
269 |
+
|
270 |
+
return None
|
271 |
+
|
272 |
+
def update_diariser(self, dia_model: Union[str, DiarisationType], **kwargs) -> None:
|
273 |
+
"""
|
274 |
+
Update the diariser model.
|
275 |
+
|
276 |
+
Args:
|
277 |
+
dia_model (Union[str, DiarisationType]):
|
278 |
+
The new diariser model to use for diarization.
|
279 |
+
**kwargs:
|
280 |
+
Additional keyword arguments for the diariser model.
|
281 |
+
|
282 |
+
Returns:
|
283 |
+
None
|
284 |
+
"""
|
285 |
+
if isinstance(dia_model, str):
|
286 |
+
self.diariser = Diariser.load_model(dia_model, **kwargs)
|
287 |
+
elif isinstance(dia_model, Diariser):
|
288 |
+
self.diariser = dia_model
|
289 |
+
else:
|
290 |
+
warn("Invalid model type. Please provide a valid model. Fallback to old Model.", RuntimeWarning)
|
291 |
+
|
292 |
+
return None
|
293 |
+
|
294 |
+
@staticmethod
|
295 |
+
def remove_audio_file(audio_file: str,
|
296 |
+
shred: bool = False) -> None:
|
297 |
+
"""
|
298 |
+
Removes the original audio file to avoid disk space issues or ensure data privacy.
|
299 |
+
|
300 |
+
Args:
|
301 |
+
audio_file_path (str): Path to the audio file.
|
302 |
+
shred (bool, optional): If True, the audio file will be shredded,
|
303 |
+
not just removed.
|
304 |
+
"""
|
305 |
+
if not os.path.exists(audio_file):
|
306 |
+
raise ValueError(f"Audiofile {audio_file} does not exist.")
|
307 |
+
|
308 |
+
if shred:
|
309 |
+
|
310 |
+
warn("Shredding audiofile can take a long time.", RuntimeWarning)
|
311 |
+
|
312 |
+
gen = iglob(f'{audio_file}', recursive=True)
|
313 |
+
cmd = ['shred', '-zvu', '-n', '10', f'{audio_file}']
|
314 |
+
|
315 |
+
if os.path.isdir(audio_file):
|
316 |
+
raise ValueError(f"Audiofile {audio_file} is a directory.")
|
317 |
+
|
318 |
+
for file in gen:
|
319 |
+
print(f'shredding {file} now\n')
|
320 |
+
|
321 |
+
run(cmd, check=True)
|
322 |
+
|
323 |
+
else:
|
324 |
+
os.remove(audio_file)
|
325 |
+
print(f"Audiofile {audio_file} removed.")
|
326 |
+
|
327 |
+
@staticmethod
|
328 |
+
def get_audio_file(audio_file: Union[str, torch.Tensor, ndarray]) -> AudioProcessor:
|
329 |
+
"""Gets an audio file as TorchAudioProcessor.
|
330 |
+
|
331 |
+
Args:
|
332 |
+
audio_file (Union[str, torch.Tensor, ndarray]): Path to the audio file or
|
333 |
+
a tensor representing the audio.
|
334 |
+
*args: Additional positional arguments.
|
335 |
+
**kwargs: Additional keyword arguments.
|
336 |
+
|
337 |
+
Returns:
|
338 |
+
AudioProcessor: An object containing the waveform and sample rate in
|
339 |
+
torch.Tensor format.
|
340 |
+
"""
|
341 |
+
|
342 |
+
if isinstance(audio_file, str):
|
343 |
+
audio_file = AudioProcessor.from_file(audio_file)
|
344 |
+
|
345 |
+
elif isinstance(audio_file, torch.Tensor):
|
346 |
+
audio_file = AudioProcessor(audio_file[0], audio_file[1])
|
347 |
+
elif isinstance(audio_file, ndarray):
|
348 |
+
audio_file = AudioProcessor(torch.Tensor(audio_file[0]),
|
349 |
+
audio_file[1])
|
350 |
+
|
351 |
+
if not isinstance(audio_file, AudioProcessor):
|
352 |
+
raise ValueError(f'Audiofile must be of type AudioProcessor,'
|
353 |
+
f'not {type(audio_file)}')
|
354 |
+
|
355 |
+
return audio_file
|
356 |
+
|
357 |
+
def __repr__(self):
|
358 |
+
return f"Scraibe(transcriber={self.transcriber}, diariser={self.diariser})"
|
scraibe/cli.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Command-Line Interface (CLI) for the Scraibe class,
|
3 |
+
allowing for user interaction to transcribe and diarize audio files.
|
4 |
+
The function includes arguments for specifying the audio files, model paths,
|
5 |
+
output formats, and other options necessary for transcription.
|
6 |
+
"""
|
7 |
+
import os
|
8 |
+
import json
|
9 |
+
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
|
10 |
+
from whisper.tokenizer import LANGUAGES, TO_LANGUAGE_CODE
|
11 |
+
from torch.cuda import is_available
|
12 |
+
from .autotranscript import Scraibe
|
13 |
+
from .misc import set_threads
|
14 |
+
|
15 |
+
def cli():
|
16 |
+
"""
|
17 |
+
Command-Line Interface (CLI) for the Scraibe class, allowing for user interaction to transcribe
|
18 |
+
and diarize audio files. The function includes arguments for specifying the audio files, model paths,
|
19 |
+
output formats, and other options necessary for transcription.
|
20 |
+
|
21 |
+
This function can be executed from the command line to perform transcription tasks, providing a
|
22 |
+
user-friendly way to access the Scraibe class functionalities.
|
23 |
+
"""
|
24 |
+
|
25 |
+
def str2bool(string):
|
26 |
+
str2val = {"True": True, "False": False}
|
27 |
+
if string in str2val:
|
28 |
+
return str2val[string]
|
29 |
+
else:
|
30 |
+
raise ValueError(
|
31 |
+
f"Expected one of {set(str2val.keys())}, got {string}")
|
32 |
+
|
33 |
+
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
|
34 |
+
|
35 |
+
parser.add_argument("-f", "--audio-files", nargs="+", type=str, default=None,
|
36 |
+
help="List of audio files to transcribe.")
|
37 |
+
|
38 |
+
parser.add_argument("--whisper-type", type=str, default="whisper",
|
39 |
+
choices=["whisper", "faster-whisper"],
|
40 |
+
help="Type of Whisper model to use ('whisper' or 'faster-whisper').")
|
41 |
+
|
42 |
+
parser.add_argument("--whisper-model-name", default="medium",
|
43 |
+
help="Name of the Whisper model to use.")
|
44 |
+
|
45 |
+
parser.add_argument("--whisper-model-directory", type=str, default=None,
|
46 |
+
help="Path to save Whisper model files; defaults to ./models/whisper.")
|
47 |
+
|
48 |
+
parser.add_argument("--diarization-directory", type=str, default=None,
|
49 |
+
help="Path to the diarization model directory.")
|
50 |
+
|
51 |
+
parser.add_argument("--hf-token", default=None, type=str,
|
52 |
+
help="HuggingFace token for private model download.")
|
53 |
+
|
54 |
+
parser.add_argument("--inference-device",
|
55 |
+
default="cuda" if is_available() else "cpu",
|
56 |
+
help="Device to use for PyTorch inference.")
|
57 |
+
|
58 |
+
parser.add_argument("--num-threads", type=int, default=None,
|
59 |
+
help="Number of threads used by torch for CPU inference; '\
|
60 |
+
'overrides MKL_NUM_THREADS/OMP_NUM_THREADS.")
|
61 |
+
|
62 |
+
parser.add_argument("--output-directory", "-o", type=str, default=".",
|
63 |
+
help="Directory to save the transcription outputs.")
|
64 |
+
|
65 |
+
parser.add_argument("--output-format", "-of", type=str, default="txt",
|
66 |
+
choices=["txt", "json", "md", "html"],
|
67 |
+
help="Format of the output file; defaults to txt.")
|
68 |
+
|
69 |
+
parser.add_argument("--verbose-output", type=str2bool, default=True,
|
70 |
+
help="Enable or disable progress and debug messages.")
|
71 |
+
|
72 |
+
parser.add_argument("--task", type=str, default='autotranscribe',
|
73 |
+
choices=["autotranscribe", "diarization",
|
74 |
+
"autotranscribe+translate", "translate", 'transcribe'],
|
75 |
+
help="Choose to perform transcription, diarization, or translation. \
|
76 |
+
If set to translate, the output will be translated to English.")
|
77 |
+
|
78 |
+
parser.add_argument("--language", type=str, default=None,
|
79 |
+
choices=sorted(
|
80 |
+
LANGUAGES.keys()) + sorted([k.title() for k in TO_LANGUAGE_CODE.keys()]),
|
81 |
+
help="Language spoken in the audio. Specify None to perform language detection.")
|
82 |
+
parser.add_argument("--num-speakers", type=int, default=2,
|
83 |
+
help="Number of speakers in the audio.")
|
84 |
+
|
85 |
+
args = parser.parse_args()
|
86 |
+
|
87 |
+
arg_dict = vars(args)
|
88 |
+
|
89 |
+
# configure output
|
90 |
+
out_folder = arg_dict.pop("output_directory")
|
91 |
+
os.makedirs(out_folder, exist_ok=True)
|
92 |
+
|
93 |
+
out_format = arg_dict.pop("output_format")
|
94 |
+
|
95 |
+
task = arg_dict.pop("task")
|
96 |
+
|
97 |
+
set_threads(arg_dict.pop("num_threads"))
|
98 |
+
|
99 |
+
class_kwargs = {'whisper_model': arg_dict.pop("whisper_model_name"),
|
100 |
+
'whisper_type':arg_dict.pop("whisper_type"),
|
101 |
+
'dia_model': arg_dict.pop("diarization_directory"),
|
102 |
+
'use_auth_token': arg_dict.pop("hf_token"),
|
103 |
+
}
|
104 |
+
|
105 |
+
if arg_dict["whisper_model_directory"]:
|
106 |
+
class_kwargs["download_root"] = arg_dict.pop("whisper_model_directory")
|
107 |
+
|
108 |
+
|
109 |
+
model = Scraibe(**class_kwargs)
|
110 |
+
|
111 |
+
if arg_dict["audio_files"]:
|
112 |
+
audio_files = arg_dict.pop("audio_files")
|
113 |
+
|
114 |
+
if task == "autotranscribe" or task == "autotranscribe+translate":
|
115 |
+
for audio in audio_files:
|
116 |
+
if task == "autotranscribe+translate":
|
117 |
+
task = "translate"
|
118 |
+
else:
|
119 |
+
task = "transcribe"
|
120 |
+
|
121 |
+
out = model.autotranscribe(
|
122 |
+
audio,
|
123 |
+
task=task,
|
124 |
+
language=arg_dict.pop("language"),
|
125 |
+
verbose=arg_dict.pop("verbose_output"),
|
126 |
+
num_speakers=arg_dict.pop("num_speakers")
|
127 |
+
)
|
128 |
+
basename = audio.split("/")[-1].split(".")[0]
|
129 |
+
print(f'Saving {basename}.{out_format} to {out_folder}')
|
130 |
+
out.save(os.path.join(
|
131 |
+
out_folder, f"{basename}.{out_format}"))
|
132 |
+
|
133 |
+
elif task == "diarization":
|
134 |
+
for audio in audio_files:
|
135 |
+
if arg_dict.pop("verbose_output"):
|
136 |
+
print("Verbose not implemented for diarization.")
|
137 |
+
|
138 |
+
out = model.diarization(audio)
|
139 |
+
basename = audio.split("/")[-1].split(".")[0]
|
140 |
+
path = os.path.join(out_folder, f"{basename}.{out_format}")
|
141 |
+
|
142 |
+
print(f'Saving {basename}.{out_format} to {out_folder}')
|
143 |
+
|
144 |
+
with open(path, "w") as f:
|
145 |
+
json.dump(json.dumps(out, indent=1), f)
|
146 |
+
|
147 |
+
elif task == "transcribe" or task == "translate":
|
148 |
+
|
149 |
+
for audio in audio_files:
|
150 |
+
|
151 |
+
out = model.transcribe(audio, task=task,
|
152 |
+
language=arg_dict.pop("language"),
|
153 |
+
verbose=arg_dict.pop("verbose_output"))
|
154 |
+
basename = audio.split("/")[-1].split(".")[0]
|
155 |
+
path = os.path.join(out_folder, f"{basename}.{out_format}")
|
156 |
+
with open(path, "w") as f:
|
157 |
+
f.write(out)
|
158 |
+
|
159 |
+
if __name__ == "__main__":
|
160 |
+
cli()
|
scraibe/diarisation.py
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Diarisation Class
|
3 |
+
------------------
|
4 |
+
|
5 |
+
This class serves as the heart of the speaker diarization system, responsible for identifying
|
6 |
+
and segmenting individual speakers from a given audio file. It leverages a pretrained model
|
7 |
+
from pyannote.audio, providing an accessible interface for audio processing tasks such as
|
8 |
+
speaker separation, and timestamping.
|
9 |
+
|
10 |
+
By encapsulating the complexities of the underlying model, it allows for straightforward
|
11 |
+
integration into various applications, ranging from transcription services to voice assistants.
|
12 |
+
|
13 |
+
Available Classes:
|
14 |
+
- Diariser: Main class for performing speaker diarization.
|
15 |
+
Includes methods for loading models, processing audio files,
|
16 |
+
and formatting the diarization output.
|
17 |
+
|
18 |
+
Constants:
|
19 |
+
- TOKEN_PATH (str): Path to the Pyannote token.
|
20 |
+
- PYANNOTE_DEFAULT_PATH (str): Default path to Pyannote models.
|
21 |
+
- PYANNOTE_DEFAULT_CONFIG (str): Default configuration for Pyannote models.
|
22 |
+
|
23 |
+
Usage:
|
24 |
+
from .diarisation import Diariser
|
25 |
+
|
26 |
+
model = Diariser.load_model(model="path/to/model/config.yaml")
|
27 |
+
diarisation_output = model.diarization("path/to/audiofile.wav")
|
28 |
+
"""
|
29 |
+
|
30 |
+
import warnings
|
31 |
+
import os
|
32 |
+
import yaml
|
33 |
+
from pathlib import Path
|
34 |
+
from typing import TypeVar, Union
|
35 |
+
|
36 |
+
from pyannote.audio import Pipeline
|
37 |
+
from pyannote.audio.pipelines.speaker_diarization import SpeakerDiarization
|
38 |
+
from torch import Tensor
|
39 |
+
from torch import device as torch_device
|
40 |
+
|
41 |
+
from huggingface_hub import HfApi
|
42 |
+
from huggingface_hub.utils import RepositoryNotFoundError
|
43 |
+
|
44 |
+
from .misc import PYANNOTE_DEFAULT_PATH, PYANNOTE_DEFAULT_CONFIG, SCRAIBE_TORCH_DEVICE
|
45 |
+
Annotation = TypeVar('Annotation')
|
46 |
+
|
47 |
+
TOKEN_PATH = os.path.join(os.path.dirname(
|
48 |
+
os.path.realpath(__file__)), '.pyannotetoken')
|
49 |
+
|
50 |
+
|
51 |
+
class Diariser:
|
52 |
+
"""
|
53 |
+
Handles the diarization process of an audio file using a pretrained model
|
54 |
+
from pyannote.audio. Diarization is the task of determining "who spoke when."
|
55 |
+
|
56 |
+
Args:
|
57 |
+
model: The pretrained model to use for diarization.
|
58 |
+
"""
|
59 |
+
|
60 |
+
def __init__(self, model) -> None:
|
61 |
+
|
62 |
+
self.model = model
|
63 |
+
|
64 |
+
def diarization(self, audiofile: Union[str, Tensor, dict],
|
65 |
+
*args, **kwargs) -> Annotation:
|
66 |
+
"""
|
67 |
+
Perform speaker diarization on the provided audio file,
|
68 |
+
effectively separating different speakers
|
69 |
+
and providing a timestamp for each segment.
|
70 |
+
|
71 |
+
Args:
|
72 |
+
audiofile: The path to the audio file or a torch.Tensor
|
73 |
+
containing the audio data.
|
74 |
+
args: Additional arguments for the diarization model.
|
75 |
+
kwargs: Additional keyword arguments for the diarization model.
|
76 |
+
|
77 |
+
Returns:
|
78 |
+
dict: A dictionary containing speaker names,
|
79 |
+
segments, and other information related
|
80 |
+
to the diarization process.
|
81 |
+
"""
|
82 |
+
kwargs = self._get_diarisation_kwargs(**kwargs)
|
83 |
+
|
84 |
+
diarization = self.model(audiofile, *args, **kwargs)
|
85 |
+
|
86 |
+
out = self.format_diarization_output(diarization)
|
87 |
+
|
88 |
+
return out
|
89 |
+
|
90 |
+
@staticmethod
|
91 |
+
def format_diarization_output(dia: Annotation) -> dict:
|
92 |
+
"""
|
93 |
+
Formats the raw diarization output into a more usable structure for this project.
|
94 |
+
|
95 |
+
Args:
|
96 |
+
dia: Raw diarization output.
|
97 |
+
|
98 |
+
Returns:
|
99 |
+
dict: A structured representation of the diarization, with speaker names
|
100 |
+
as keys and a list of tuples representing segments as values.
|
101 |
+
"""
|
102 |
+
|
103 |
+
dia_list = list(dia.itertracks(yield_label=True))
|
104 |
+
diarization_output = {"speakers": [], "segments": []}
|
105 |
+
|
106 |
+
normalized_output = []
|
107 |
+
index_start_speaker = 0
|
108 |
+
index_end_speaker = 0
|
109 |
+
current_speaker = str()
|
110 |
+
|
111 |
+
###
|
112 |
+
# Sometimes two consecutive speakers are the same
|
113 |
+
# This loop removes these duplicates
|
114 |
+
###
|
115 |
+
|
116 |
+
if len(dia_list) == 1:
|
117 |
+
normalized_output.append([0, 0, dia_list[0][2]])
|
118 |
+
else:
|
119 |
+
|
120 |
+
for i, (_, _, speaker) in enumerate(dia_list):
|
121 |
+
|
122 |
+
if i == 0:
|
123 |
+
current_speaker = speaker
|
124 |
+
|
125 |
+
if speaker != current_speaker:
|
126 |
+
|
127 |
+
index_end_speaker = i - 1
|
128 |
+
|
129 |
+
normalized_output.append([index_start_speaker,
|
130 |
+
index_end_speaker,
|
131 |
+
current_speaker])
|
132 |
+
|
133 |
+
index_start_speaker = i
|
134 |
+
current_speaker = speaker
|
135 |
+
|
136 |
+
if i == len(dia_list) - 1:
|
137 |
+
|
138 |
+
index_end_speaker = i
|
139 |
+
|
140 |
+
normalized_output.append([index_start_speaker,
|
141 |
+
index_end_speaker,
|
142 |
+
current_speaker])
|
143 |
+
|
144 |
+
for outp in normalized_output:
|
145 |
+
start = dia_list[outp[0]][0].start
|
146 |
+
end = dia_list[outp[1]][0].end
|
147 |
+
|
148 |
+
diarization_output["segments"].append([start, end])
|
149 |
+
diarization_output["speakers"].append(outp[2])
|
150 |
+
return diarization_output
|
151 |
+
|
152 |
+
@staticmethod
|
153 |
+
def _get_token():
|
154 |
+
"""
|
155 |
+
Retrieves the Huggingface token from a local file. This token is required
|
156 |
+
for accessing certain online resources.
|
157 |
+
|
158 |
+
Raises:
|
159 |
+
ValueError: If the token is not found.
|
160 |
+
|
161 |
+
Returns:
|
162 |
+
str: The Huggingface token.
|
163 |
+
"""
|
164 |
+
|
165 |
+
if os.path.exists(TOKEN_PATH):
|
166 |
+
with open(TOKEN_PATH, 'r', encoding="utf-8") as file:
|
167 |
+
token = file.read()
|
168 |
+
else:
|
169 |
+
raise ValueError('No token found.'
|
170 |
+
'Please create a token at https://huggingface.co/settings/token'
|
171 |
+
f'and save it in a file called {TOKEN_PATH}')
|
172 |
+
return token
|
173 |
+
|
174 |
+
@staticmethod
|
175 |
+
def _save_token(token):
|
176 |
+
"""
|
177 |
+
Saves the provided Huggingface token to a local file. This facilitates future
|
178 |
+
access to online resources without needing to repeatedly authenticate.
|
179 |
+
|
180 |
+
Args:
|
181 |
+
token: The Huggingface token to save.
|
182 |
+
"""
|
183 |
+
with open(TOKEN_PATH, 'w', encoding="utf-8") as file:
|
184 |
+
file.write(token)
|
185 |
+
|
186 |
+
@classmethod
|
187 |
+
def load_model(cls,
|
188 |
+
model: str = PYANNOTE_DEFAULT_CONFIG,
|
189 |
+
use_auth_token: str = None,
|
190 |
+
cache_token: bool = False,
|
191 |
+
cache_dir: Union[Path, str] = PYANNOTE_DEFAULT_PATH,
|
192 |
+
hparams_file: Union[str, Path] = None,
|
193 |
+
device: str = SCRAIBE_TORCH_DEVICE,
|
194 |
+
) -> Pipeline:
|
195 |
+
"""
|
196 |
+
Loads a pretrained model from pyannote.audio,
|
197 |
+
either from a local cache or some online repository.
|
198 |
+
|
199 |
+
Args:
|
200 |
+
model: Path or identifier for the pyannote model.
|
201 |
+
default: '/home/[user]/.cache/torch/models/pyannote/config.yaml'
|
202 |
+
or one of 'jaikinator/scraibe', 'pyannote/speaker-diarization-3.1'
|
203 |
+
token: Optional HUGGINGFACE_TOKEN for authenticated access.
|
204 |
+
cache_token: Whether to cache the token locally for future use.
|
205 |
+
cache_dir: Directory for caching models.
|
206 |
+
hparams_file: Path to a YAML file containing hyperparameters.
|
207 |
+
device: Device to load the model on.
|
208 |
+
args: Additional arguments only to avoid errors.
|
209 |
+
kwargs: Additional keyword arguments only to avoid errors.
|
210 |
+
|
211 |
+
Returns:
|
212 |
+
Pipeline: A pyannote.audio Pipeline object, encapsulating the loaded model.
|
213 |
+
"""
|
214 |
+
if isinstance(model, str) and os.path.exists(model):
|
215 |
+
# check if model can be found locally nearby the config file
|
216 |
+
with open(model, 'r') as file:
|
217 |
+
config = yaml.safe_load(file)
|
218 |
+
|
219 |
+
path_to_model = config['pipeline']['params']['segmentation']
|
220 |
+
|
221 |
+
if not os.path.exists(path_to_model):
|
222 |
+
warnings.warn(f"Model not found at {path_to_model}. "
|
223 |
+
"Trying to find it nearby the config file.")
|
224 |
+
|
225 |
+
pwd = model.split("/")[:-1]
|
226 |
+
pwd = "/".join(pwd)
|
227 |
+
|
228 |
+
path_to_model = os.path.join(pwd, "pytorch_model.bin")
|
229 |
+
|
230 |
+
if not os.path.exists(path_to_model):
|
231 |
+
warnings.warn(f"Model not found at {path_to_model}. \
|
232 |
+
'Trying to find it nearby .bin files instead.")
|
233 |
+
warnings.warn(
|
234 |
+
'Searching for nearby files in a folder path is '
|
235 |
+
'deprecated and will be removed in future versions.',
|
236 |
+
category=DeprecationWarning)
|
237 |
+
# list elementes with the ending .bin
|
238 |
+
bin_files = [f for f in os.listdir(
|
239 |
+
pwd) if f.endswith(".bin")]
|
240 |
+
if len(bin_files) == 1:
|
241 |
+
path_to_model = os.path.join(pwd, bin_files[0])
|
242 |
+
else:
|
243 |
+
warnings.warn("Found more than one .bin file. "
|
244 |
+
"or none. Please specify the path to the model "
|
245 |
+
"or setup a huggingface token.")
|
246 |
+
raise FileNotFoundError
|
247 |
+
|
248 |
+
warnings.warn(
|
249 |
+
f"Found model at {path_to_model} overwriting config file.")
|
250 |
+
|
251 |
+
config['pipeline']['params']['segmentation'] = path_to_model
|
252 |
+
|
253 |
+
with open(model, 'w') as file:
|
254 |
+
yaml.dump(config, file)
|
255 |
+
elif isinstance(model, tuple):
|
256 |
+
try:
|
257 |
+
_model = model[0]
|
258 |
+
HfApi().model_info(_model)
|
259 |
+
model = _model
|
260 |
+
use_auth_token = None
|
261 |
+
except RepositoryNotFoundError:
|
262 |
+
print(f'{model[0]} not found on Huggingface, \
|
263 |
+
trying {model[1]}')
|
264 |
+
_model = model[1]
|
265 |
+
HfApi().model_info(_model)
|
266 |
+
model = _model
|
267 |
+
if cache_token and use_auth_token is not None:
|
268 |
+
cls._save_token(use_auth_token)
|
269 |
+
|
270 |
+
if use_auth_token is None:
|
271 |
+
use_auth_token = cls._get_token()
|
272 |
+
else:
|
273 |
+
raise FileNotFoundError(
|
274 |
+
f'No local model or directory found at {model}.')
|
275 |
+
|
276 |
+
_model = Pipeline.from_pretrained(model,
|
277 |
+
use_auth_token=use_auth_token,
|
278 |
+
cache_dir=cache_dir,
|
279 |
+
hparams_file=hparams_file,)
|
280 |
+
if _model is None:
|
281 |
+
raise ValueError('Unable to load model either from local cache'
|
282 |
+
'or from huggingface.co models. Please check your token'
|
283 |
+
'or your local model path')
|
284 |
+
|
285 |
+
# torch_device is renamed from torch.device to avoid name conflict
|
286 |
+
_model = _model.to(torch_device(device))
|
287 |
+
|
288 |
+
return cls(_model)
|
289 |
+
|
290 |
+
@staticmethod
|
291 |
+
def _get_diarisation_kwargs(**kwargs) -> dict:
|
292 |
+
"""
|
293 |
+
Validates and extracts the keyword arguments for the pyannote diarization model.
|
294 |
+
|
295 |
+
Ensures that the provided keyword arguments match the expected parameters,
|
296 |
+
filtering out any invalid or unnecessary arguments.
|
297 |
+
|
298 |
+
Returns:
|
299 |
+
dict: A dictionary containing the validated keyword arguments.
|
300 |
+
"""
|
301 |
+
_possible_kwargs = SpeakerDiarization.apply.__code__.co_varnames
|
302 |
+
|
303 |
+
diarisation_kwargs = {k: v for k,
|
304 |
+
v in kwargs.items() if k in _possible_kwargs}
|
305 |
+
|
306 |
+
return diarisation_kwargs
|
307 |
+
|
308 |
+
def __repr__(self):
|
309 |
+
return f"Diarisation(model={self.model})"
|
scraibe/hallucinations.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# List of known hallucinations - adapted from:
|
2 |
+
# https://github.com/openai/whisper/discussions/928
|
3 |
+
KNOWN_HALLUCINATIONS = [
|
4 |
+
# en
|
5 |
+
" www.mooji.org"
|
6 |
+
# nl
|
7 |
+
" Ondertitels ingediend door de Amara.org gemeenschap",
|
8 |
+
" Ondertiteld door de Amara.org gemeenschap",
|
9 |
+
" Ondertiteling door de Amara.org gemeenschap"
|
10 |
+
# de
|
11 |
+
" Untertitelung aufgrund der Amara.org-Community"
|
12 |
+
" Untertitelung im Auftrag des ZDF für funk, 2016",
|
13 |
+
" Untertitelung im Auftrag des ZDF f\u00fcr funk, 2016",
|
14 |
+
" Untertitel im Auftrag des ZDF für funk, 2017",
|
15 |
+
" Untertitel im Auftrag des ZDF f\u00fcr funk, 2017",
|
16 |
+
" Untertitel im Auftrag des ZDF für funk, 2018",
|
17 |
+
" Untertitel von Stephanie Geiges",
|
18 |
+
" Untertitel der Amara.org-Community",
|
19 |
+
" Untertitel im Auftrag des ZDF, 2017",
|
20 |
+
" Untertitel im Auftrag des ZDF, 2018",
|
21 |
+
" Untertitel im Auftrag des ZDF, 2019",
|
22 |
+
" Untertitel im Auftrag des ZDF, 2020",
|
23 |
+
" Untertitel im Auftrag des ZDF, 2021",
|
24 |
+
" Untertitelung im Auftrag des ZDF, 2021",
|
25 |
+
" Copyright WDR 2021",
|
26 |
+
" Copyright WDR 2020",
|
27 |
+
" Copyright WDR 2019",
|
28 |
+
" SWR 2021",
|
29 |
+
" SWR 2020",
|
30 |
+
# fr
|
31 |
+
" Sous-titres réalisés para la communauté d'Amara.org",
|
32 |
+
" Sous-titres réalisés par la communauté d'Amara.org",
|
33 |
+
" Sous-titres fait par Sous-titres par Amara.org",
|
34 |
+
" Sous-titres réalisés par les SousTitres d'Amara.org",
|
35 |
+
" Sous-titres par Amara.org",
|
36 |
+
" Sous-titres par la communauté d'Amara.org",
|
37 |
+
" Sous-titres réalisés pour la communauté d'Amara.org",
|
38 |
+
" Sous-titres réalisés par la communauté de l'Amara.org",
|
39 |
+
" Sous-Titres faits par la communauté d'Amara.org",
|
40 |
+
" Sous-titres par l'Amara.org",
|
41 |
+
" Sous-titres fait par la communauté d'Amara.org"
|
42 |
+
" Sous-titrage ST' 501",
|
43 |
+
" Sous-titrage ST'501",
|
44 |
+
" Cliquez-vous sur les sous-titres et abonnez-vous à la chaîne d'Amara.org",
|
45 |
+
" ❤️ par SousTitreur.com",
|
46 |
+
# it
|
47 |
+
" Sottotitoli creati dalla comunità Amara.org",
|
48 |
+
" Sottotitoli di Sottotitoli di Amara.org",
|
49 |
+
" Sottotitoli e revisione al canale di Amara.org",
|
50 |
+
" Sottotitoli e revisione a cura di Amara.org",
|
51 |
+
" Sottotitoli e revisione a cura di QTSS",
|
52 |
+
" Sottotitoli e revisione a cura di QTSS.",
|
53 |
+
" Sottotitoli a cura di QTSS",
|
54 |
+
" Subtítulos realizados por la comunidad de Amara.org",
|
55 |
+
" Subtitulado por la comunidad de Amara.org",
|
56 |
+
" Subtítulos por la comunidad de Amara.org",
|
57 |
+
" Subtítulos creados por la comunidad de Amara.org",
|
58 |
+
" Subtítulos en español de Amara.org",
|
59 |
+
" Subtítulos hechos por la comunidad de Amara.org",
|
60 |
+
" Subtitulos por la comunidad de Amara.org"
|
61 |
+
" Más información www.alimmenta.com",
|
62 |
+
" www.mooji.org",
|
63 |
+
# gl
|
64 |
+
" Subtítulos realizados por la comunidad de Amara.org"
|
65 |
+
# pt
|
66 |
+
" Legendas pela comunidade Amara.org",
|
67 |
+
" Legendas pela comunidade de Amara.org",
|
68 |
+
" Legendas pela comunidade do Amara.org",
|
69 |
+
" Legendas pela comunidade das Amara.org",
|
70 |
+
" Transcrição e Legendas pela comunidade de Amara.org"
|
71 |
+
# la
|
72 |
+
" Sottotitoli creati dalla comunità Amara.org",
|
73 |
+
" Sous-titres réalisés para la communauté d'Amara.org"
|
74 |
+
# ln
|
75 |
+
" Sous-titres réalisés para la communauté d'Amara.org"
|
76 |
+
# pl
|
77 |
+
" Napisy stworzone przez społeczność Amara.org",
|
78 |
+
" Napisy wykonane przez społeczność Amara.org",
|
79 |
+
" Zdjęcia i napisy stworzone przez społeczność Amara.org",
|
80 |
+
" napisy stworzone przez społeczność Amara.org",
|
81 |
+
" Tłumaczenie i napisy stworzone przez społeczność Amara.org",
|
82 |
+
" Napisy stworzone przez społeczności Amara.org",
|
83 |
+
" Tłumaczenie stworzone przez społeczność Amara.org",
|
84 |
+
" Napisy robione przez społeczność Amara.org"
|
85 |
+
" www.multi-moto.eu",
|
86 |
+
# ru
|
87 |
+
" Редактор субтитров А.Синецкая Корректор А.Егорова"
|
88 |
+
# tr
|
89 |
+
" Yorumlarınızıza abone olmayı unutmayın.",
|
90 |
+
# su
|
91 |
+
" Sottotitoli creati dalla comunità Amara.org"
|
92 |
+
# zh
|
93 |
+
"字幕由Amara.org社区提供",
|
94 |
+
"小編字幕由Amara.org社區提供"
|
95 |
+
]
|
scraibe/misc.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import yaml
|
3 |
+
from argparse import Action
|
4 |
+
from ast import literal_eval
|
5 |
+
from torch.cuda import is_available
|
6 |
+
from torch import get_num_threads, set_num_threads
|
7 |
+
|
8 |
+
CACHE_DIR = os.getenv(
|
9 |
+
"AUTOT_CACHE",
|
10 |
+
os.path.expanduser("~/.cache/torch/models"),
|
11 |
+
)
|
12 |
+
os.environ["PYANNOTE_CACHE"] = os.getenv(
|
13 |
+
"PYANNOTE_CACHE",
|
14 |
+
os.path.join(CACHE_DIR, "pyannote"),
|
15 |
+
)
|
16 |
+
|
17 |
+
WHISPER_DEFAULT_PATH = os.path.join(CACHE_DIR, "whisper")
|
18 |
+
PYANNOTE_DEFAULT_PATH = os.path.join(CACHE_DIR, "pyannote")
|
19 |
+
PYANNOTE_DEFAULT_CONFIG = os.path.join(PYANNOTE_DEFAULT_PATH, "config.yaml") \
|
20 |
+
if os.path.exists(os.path.join(PYANNOTE_DEFAULT_PATH, "config.yaml")) \
|
21 |
+
else ('Jaikinator/ScrAIbe', 'pyannote/speaker-diarization-3.1')
|
22 |
+
|
23 |
+
SCRAIBE_TORCH_DEVICE = os.getenv("SCRAIBE_TORCH_DEVICE", "cuda" if is_available() else "cpu")
|
24 |
+
|
25 |
+
SCRAIBE_NUM_THREADS = os.getenv("SCRAIBE_NUM_THREADS", min(8, get_num_threads()))
|
26 |
+
|
27 |
+
def config_diarization_yaml(file_path: str, path_to_segmentation: str = None) -> None:
|
28 |
+
"""Configure diarization pipeline from a YAML file.
|
29 |
+
|
30 |
+
This function updates the YAML file to use the given segmentation model
|
31 |
+
offline, and avoids manual file manipulation.
|
32 |
+
|
33 |
+
Args:
|
34 |
+
file_path (str): Path to the YAML file.
|
35 |
+
path_to_segmentation (str, optional): Optional path to the segmentation model.
|
36 |
+
|
37 |
+
Raises:
|
38 |
+
FileNotFoundError: If the segmentation model file is not found.
|
39 |
+
"""
|
40 |
+
with open(file_path, "r") as stream:
|
41 |
+
yml = yaml.safe_load(stream)
|
42 |
+
|
43 |
+
segmentation_path = path_to_segmentation or os.path.join(
|
44 |
+
PYANNOTE_DEFAULT_PATH, "pytorch_model.bin")
|
45 |
+
yml["pipeline"]["params"]["segmentation"] = segmentation_path
|
46 |
+
|
47 |
+
if not os.path.exists(segmentation_path):
|
48 |
+
raise FileNotFoundError(
|
49 |
+
f"Segmentation model not found at {segmentation_path}")
|
50 |
+
|
51 |
+
with open(file_path, "w") as stream:
|
52 |
+
yaml.dump(yml, stream)
|
53 |
+
|
54 |
+
|
55 |
+
def set_threads(parse_threads=None,
|
56 |
+
yaml_threads=None):
|
57 |
+
global SCRAIBE_NUM_THREADS
|
58 |
+
if parse_threads is not None:
|
59 |
+
if not isinstance(parse_threads, int):
|
60 |
+
# probably covered with int type of parser arg
|
61 |
+
raise ValueError(f"Type of --num-threads must be int, but the type is {type(parse_threads)}")
|
62 |
+
elif parse_threads < 1:
|
63 |
+
raise ValueError(f"Number of threads must be a positive integer, {parse_threads} was given")
|
64 |
+
else:
|
65 |
+
set_num_threads(parse_threads)
|
66 |
+
SCRAIBE_NUM_THREADS = parse_threads
|
67 |
+
elif yaml_threads is not None:
|
68 |
+
if not isinstance(yaml_threads, int):
|
69 |
+
raise ValueError(f"Type of num_threads must be int, but the type is {type(yaml_threads)}")
|
70 |
+
elif yaml_threads < 1:
|
71 |
+
raise ValueError(f"Number of threads must be a positive integer, {yaml_threads} was given")
|
72 |
+
else:
|
73 |
+
set_num_threads(yaml_threads)
|
74 |
+
SCRAIBE_NUM_THREADS = yaml_threads
|
75 |
+
|
76 |
+
class ParseKwargs(Action):
|
77 |
+
"""
|
78 |
+
Custom argparse action to parse keyword arguments.
|
79 |
+
"""
|
80 |
+
|
81 |
+
def __call__(self, parser, namespace, values, option_string=None):
|
82 |
+
setattr(namespace, self.dest, dict())
|
83 |
+
for value in values:
|
84 |
+
key, value = value.split('=')
|
85 |
+
try:
|
86 |
+
value = literal_eval(value)
|
87 |
+
except:
|
88 |
+
pass
|
89 |
+
getattr(namespace, self.dest)[key] = value
|
scraibe/transcriber.py
ADDED
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Transcriber Module
|
3 |
+
------------------
|
4 |
+
|
5 |
+
This module provides the Transcriber class, a comprehensive tool for working with Whisper models.
|
6 |
+
The Transcriber class offers functionalities such as loading different Whisper models, transcribing audio files,
|
7 |
+
and saving transcriptions to text files. It acts as an interface between various Whisper models and the user,
|
8 |
+
simplifying the process of audio transcription.
|
9 |
+
|
10 |
+
Main Features:
|
11 |
+
- Loading different sizes and versions of Whisper models.
|
12 |
+
- Transcribing audio in various formats including str, Tensor, and nparray.
|
13 |
+
- Saving the transcriptions to the specified paths.
|
14 |
+
- Adaptable to various language specifications.
|
15 |
+
- Options to control the verbosity of the transcription process.
|
16 |
+
|
17 |
+
Constants:
|
18 |
+
WHISPER_DEFAULT_PATH: Default path for downloading and loading Whisper models.
|
19 |
+
|
20 |
+
Usage:
|
21 |
+
>>> from your_package import Transcriber
|
22 |
+
>>> transcriber = Transcriber.load_model(model="medium")
|
23 |
+
>>> transcript = transcriber.transcribe(audio="path/to/audio.wav")
|
24 |
+
>>> transcriber.save_transcript(transcript, "path/to/save.txt")
|
25 |
+
"""
|
26 |
+
|
27 |
+
from whisper import Whisper
|
28 |
+
from whisper import load_model as whisper_load_model
|
29 |
+
from whisper.tokenizer import TO_LANGUAGE_CODE
|
30 |
+
from faster_whisper import WhisperModel as FasterWhisperModel
|
31 |
+
from faster_whisper.tokenizer import _LANGUAGE_CODES as FASTER_WHISPER_LANGUAGE_CODES
|
32 |
+
from typing import TypeVar, Union, Optional
|
33 |
+
from torch import Tensor, device
|
34 |
+
from numpy import ndarray
|
35 |
+
from inspect import signature
|
36 |
+
from abc import abstractmethod
|
37 |
+
import warnings
|
38 |
+
|
39 |
+
from .misc import WHISPER_DEFAULT_PATH, SCRAIBE_TORCH_DEVICE, SCRAIBE_NUM_THREADS
|
40 |
+
whisper = TypeVar('whisper')
|
41 |
+
|
42 |
+
|
43 |
+
class Transcriber:
|
44 |
+
"""
|
45 |
+
Transcriber Class
|
46 |
+
-----------------
|
47 |
+
|
48 |
+
The Transcriber class serves as a wrapper around Whisper models for efficient audio
|
49 |
+
transcription. By encapsulating the intricacies of loading models, processing audio,
|
50 |
+
and saving transcripts, it offers an easy-to-use interface
|
51 |
+
for users to transcribe audio files.
|
52 |
+
|
53 |
+
Attributes:
|
54 |
+
model (whisper): The Whisper model used for transcription.
|
55 |
+
|
56 |
+
Methods:
|
57 |
+
transcribe: Transcribes the given audio file.
|
58 |
+
save_transcript: Saves the transcript to a file.
|
59 |
+
load_model: Loads a specific Whisper model.
|
60 |
+
_get_whisper_kwargs: Private method to get valid keyword arguments for the whisper model.
|
61 |
+
|
62 |
+
Examples:
|
63 |
+
>>> transcriber = Transcriber.load_model(model="medium")
|
64 |
+
>>> transcript = transcriber.transcribe(audio="path/to/audio.wav")
|
65 |
+
>>> transcriber.save_transcript(transcript, "path/to/save.txt")
|
66 |
+
|
67 |
+
Note:
|
68 |
+
The class supports various sizes and versions of Whisper models. Please refer to
|
69 |
+
the load_model method for available options.
|
70 |
+
"""
|
71 |
+
|
72 |
+
def __init__(self, model: whisper, model_name: str) -> None:
|
73 |
+
"""
|
74 |
+
Initialize the Transcriber class with a Whisper model.
|
75 |
+
|
76 |
+
Args:
|
77 |
+
model (whisper): The Whisper model to use for transcription.
|
78 |
+
model_name (str): The name of the model.
|
79 |
+
"""
|
80 |
+
|
81 |
+
self.model = model
|
82 |
+
|
83 |
+
self.model_name = model_name
|
84 |
+
|
85 |
+
@abstractmethod
|
86 |
+
def transcribe(self, audio: Union[str, Tensor, ndarray],
|
87 |
+
*args, **kwargs) -> str:
|
88 |
+
"""
|
89 |
+
Transcribe an audio file.
|
90 |
+
|
91 |
+
Args:
|
92 |
+
audio (Union[str, Tensor, nparray]): The audio file to transcribe.
|
93 |
+
*args: Additional arguments.
|
94 |
+
**kwargs: Additional keyword arguments,
|
95 |
+
such as the language of the audio file.
|
96 |
+
|
97 |
+
Returns:
|
98 |
+
str: The transcript as a string.
|
99 |
+
"""
|
100 |
+
pass
|
101 |
+
|
102 |
+
@staticmethod
|
103 |
+
def save_transcript(transcript: str, save_path: str) -> None:
|
104 |
+
"""
|
105 |
+
Save a transcript to a file.
|
106 |
+
|
107 |
+
Args:
|
108 |
+
transcript (str): The transcript as a string.
|
109 |
+
save_path (str): The path to save the transcript.
|
110 |
+
|
111 |
+
Returns:
|
112 |
+
None
|
113 |
+
"""
|
114 |
+
|
115 |
+
with open(save_path, 'w') as f:
|
116 |
+
f.write(transcript)
|
117 |
+
|
118 |
+
print(f'Transcript saved to {save_path}')
|
119 |
+
|
120 |
+
@classmethod
|
121 |
+
@abstractmethod
|
122 |
+
def load_model(cls,
|
123 |
+
model: str = "large-v3",
|
124 |
+
whisper_type: str = 'whisper',
|
125 |
+
download_root: str = WHISPER_DEFAULT_PATH,
|
126 |
+
device: Optional[Union[str, device]] = SCRAIBE_TORCH_DEVICE,
|
127 |
+
in_memory: bool = False,
|
128 |
+
*args, **kwargs
|
129 |
+
) -> None:
|
130 |
+
"""
|
131 |
+
Load whisper model.
|
132 |
+
|
133 |
+
Args:
|
134 |
+
model (str): Whisper model. Available models include:
|
135 |
+
- 'tiny.en'
|
136 |
+
- 'tiny'
|
137 |
+
- 'base.en'
|
138 |
+
- 'base'
|
139 |
+
- 'small.en'
|
140 |
+
- 'small'
|
141 |
+
- 'medium.en'
|
142 |
+
- 'medium'
|
143 |
+
- 'large-v1'
|
144 |
+
- 'large-v2'
|
145 |
+
- 'large-v3'
|
146 |
+
- 'large'
|
147 |
+
whisper_type (str):
|
148 |
+
Type of whisper model to load. "whisper" or "faster-whisper".
|
149 |
+
download_root (str, optional): Path to download the model.
|
150 |
+
Defaults to WHISPER_DEFAULT_PATH.
|
151 |
+
device (Optional[Union[str, torch.device]], optional):
|
152 |
+
Device to load model on. Defaults to None.
|
153 |
+
in_memory (bool, optional): Whether to load model in memory.
|
154 |
+
Defaults to False.
|
155 |
+
args: Additional arguments only to avoid errors.
|
156 |
+
kwargs: Additional keyword arguments only to avoid errors.
|
157 |
+
|
158 |
+
Returns:
|
159 |
+
None: abscract method.
|
160 |
+
"""
|
161 |
+
pass
|
162 |
+
|
163 |
+
@staticmethod
|
164 |
+
def _get_whisper_kwargs(**kwargs) -> dict:
|
165 |
+
"""
|
166 |
+
Get kwargs for whisper model. Ensure that kwargs are valid.
|
167 |
+
|
168 |
+
Returns:
|
169 |
+
dict: Keyword arguments for whisper model.
|
170 |
+
"""
|
171 |
+
pass
|
172 |
+
|
173 |
+
def __repr__(self) -> str:
|
174 |
+
return f"Transcriber(model_name={self.model_name}, model={self.model})"
|
175 |
+
|
176 |
+
|
177 |
+
class WhisperTranscriber(Transcriber):
|
178 |
+
def __init__(self, model: whisper, model_name: str) -> None:
|
179 |
+
super().__init__(model, model_name)
|
180 |
+
|
181 |
+
def transcribe(self, audio: Union[str, Tensor, ndarray],
|
182 |
+
*args, **kwargs) -> str:
|
183 |
+
"""
|
184 |
+
Transcribe an audio file.
|
185 |
+
|
186 |
+
Args:
|
187 |
+
audio (Union[str, Tensor, nparray]): The audio file to transcribe.
|
188 |
+
*args: Additional arguments.
|
189 |
+
**kwargs: Additional keyword arguments,
|
190 |
+
such as the language of the audio file.
|
191 |
+
|
192 |
+
Returns:
|
193 |
+
str: The transcript as a string.
|
194 |
+
"""
|
195 |
+
|
196 |
+
kwargs = self._get_whisper_kwargs(**kwargs)
|
197 |
+
|
198 |
+
if not kwargs.get("verbose"):
|
199 |
+
kwargs["verbose"] = None
|
200 |
+
|
201 |
+
result = self.model.transcribe(audio, *args, **kwargs)
|
202 |
+
return result["text"]
|
203 |
+
|
204 |
+
@classmethod
|
205 |
+
def load_model(cls,
|
206 |
+
model: str = "large-v3",
|
207 |
+
download_root: str = WHISPER_DEFAULT_PATH,
|
208 |
+
device: Optional[Union[str, device]] = SCRAIBE_TORCH_DEVICE,
|
209 |
+
in_memory: bool = False,
|
210 |
+
*args, **kwargs
|
211 |
+
) -> 'WhisperTranscriber':
|
212 |
+
"""
|
213 |
+
Load whisper model.
|
214 |
+
|
215 |
+
Args:
|
216 |
+
model (str): Whisper model. Available models include:
|
217 |
+
- 'tiny.en'
|
218 |
+
- 'tiny'
|
219 |
+
- 'base.en'
|
220 |
+
- 'base'
|
221 |
+
- 'small.en'
|
222 |
+
- 'small'
|
223 |
+
- 'medium.en'
|
224 |
+
- 'medium'
|
225 |
+
- 'large-v1'
|
226 |
+
- 'large-v2'
|
227 |
+
- 'large-v3'
|
228 |
+
- 'large'
|
229 |
+
|
230 |
+
download_root (str, optional): Path to download the model.
|
231 |
+
Defaults to WHISPER_DEFAULT_PATH.
|
232 |
+
|
233 |
+
device (Optional[Union[str, torch.device]], optional):
|
234 |
+
Device to load model on. Defaults to None.
|
235 |
+
in_memory (bool, optional): Whether to load model in memory.
|
236 |
+
Defaults to False.
|
237 |
+
args: Additional arguments only to avoid errors.
|
238 |
+
kwargs: Additional keyword arguments only to avoid errors.
|
239 |
+
|
240 |
+
Returns:
|
241 |
+
Transcriber: A Transcriber object initialized with the specified model.
|
242 |
+
"""
|
243 |
+
|
244 |
+
_model = whisper_load_model(model, download_root=download_root,
|
245 |
+
device=device, in_memory=in_memory)
|
246 |
+
|
247 |
+
return cls(_model, model_name=model)
|
248 |
+
|
249 |
+
@staticmethod
|
250 |
+
def _get_whisper_kwargs(**kwargs) -> dict:
|
251 |
+
"""
|
252 |
+
Get kwargs for whisper model. Ensure that kwargs are valid.
|
253 |
+
|
254 |
+
Returns:
|
255 |
+
dict: Keyword arguments for whisper model.
|
256 |
+
"""
|
257 |
+
# _possible_kwargs = WhisperModel.transcribe.__code__.co_varnames
|
258 |
+
_possible_kwargs = signature(Whisper.transcribe).parameters.keys()
|
259 |
+
|
260 |
+
whisper_kwargs = {k: v for k,
|
261 |
+
v in kwargs.items() if k in _possible_kwargs}
|
262 |
+
|
263 |
+
if (task := kwargs.get("task")):
|
264 |
+
whisper_kwargs["task"] = task
|
265 |
+
|
266 |
+
if (language := kwargs.get("language")):
|
267 |
+
whisper_kwargs["language"] = language
|
268 |
+
|
269 |
+
return whisper_kwargs
|
270 |
+
|
271 |
+
def __repr__(self) -> str:
|
272 |
+
return f"WhisperTranscriber(model_name={self.model_name}, model={self.model})"
|
273 |
+
|
274 |
+
|
275 |
+
class FasterWhisperTranscriber(Transcriber):
|
276 |
+
def __init__(self, model: whisper, model_name: str) -> None:
|
277 |
+
super().__init__(model, model_name)
|
278 |
+
|
279 |
+
def transcribe(self, audio: Union[str, Tensor, ndarray],
|
280 |
+
*args, **kwargs) -> str:
|
281 |
+
"""
|
282 |
+
Transcribe an audio file.
|
283 |
+
|
284 |
+
Args:
|
285 |
+
audio (Union[str, Tensor, nparray]): The audio file to transcribe.
|
286 |
+
*args: Additional arguments.
|
287 |
+
**kwargs: Additional keyword arguments,
|
288 |
+
such as the language of the audio file.
|
289 |
+
|
290 |
+
Returns:
|
291 |
+
str: The transcript as a string.
|
292 |
+
"""
|
293 |
+
kwargs = self._get_whisper_kwargs(**kwargs)
|
294 |
+
|
295 |
+
if isinstance(audio, Tensor):
|
296 |
+
audio = audio.cpu().numpy()
|
297 |
+
result, _ = self.model.transcribe(audio, *args, **kwargs)
|
298 |
+
text = ""
|
299 |
+
for seg in result:
|
300 |
+
text += seg.text
|
301 |
+
return text
|
302 |
+
|
303 |
+
@classmethod
|
304 |
+
def load_model(cls,
|
305 |
+
model: str = "large-v3",
|
306 |
+
download_root: str = WHISPER_DEFAULT_PATH,
|
307 |
+
device: Optional[Union[str, device]] = SCRAIBE_TORCH_DEVICE,
|
308 |
+
*args, **kwargs
|
309 |
+
) -> 'FasterWhisperModel':
|
310 |
+
"""
|
311 |
+
Load whisper model.
|
312 |
+
|
313 |
+
Args:
|
314 |
+
model (str): Whisper model. Available models include:
|
315 |
+
- 'tiny.en'
|
316 |
+
- 'tiny'
|
317 |
+
- 'base.en'
|
318 |
+
- 'base'
|
319 |
+
- 'small.en'
|
320 |
+
- 'small'
|
321 |
+
- 'medium.en'
|
322 |
+
- 'medium'
|
323 |
+
- 'large-v1'
|
324 |
+
- 'large-v2'
|
325 |
+
- 'large-v3'
|
326 |
+
- 'large'
|
327 |
+
|
328 |
+
download_root (str, optional): Path to download the model.
|
329 |
+
Defaults to WHISPER_DEFAULT_PATH.
|
330 |
+
|
331 |
+
device (Optional[Union[str, torch.device]], optional):
|
332 |
+
Device to load model on. Defaults to SCRAIBE_TORCH_DEVICE.
|
333 |
+
in_memory (bool, optional): Whether to load model in memory.
|
334 |
+
Defaults to False.
|
335 |
+
args: Additional arguments only to avoid errors.
|
336 |
+
kwargs: Additional keyword arguments only to avoid errors.
|
337 |
+
|
338 |
+
Returns:
|
339 |
+
Transcriber: A Transcriber object initialized with the specified model.
|
340 |
+
"""
|
341 |
+
|
342 |
+
if not isinstance(device, str):
|
343 |
+
device = str(device)
|
344 |
+
|
345 |
+
compute_type = kwargs.get('compute_type', 'float16')
|
346 |
+
if device == 'cpu' and compute_type == 'float16':
|
347 |
+
warnings.warn(f'Compute type {compute_type} not compatible with '
|
348 |
+
f'device {device}! Changing compute type to int8.')
|
349 |
+
compute_type = 'int8'
|
350 |
+
_model = FasterWhisperModel(model, download_root=download_root,
|
351 |
+
device=device, compute_type=compute_type,
|
352 |
+
cpu_threads=SCRAIBE_NUM_THREADS)
|
353 |
+
|
354 |
+
return cls(_model, model_name=model)
|
355 |
+
|
356 |
+
@staticmethod
|
357 |
+
def _get_whisper_kwargs(**kwargs) -> dict:
|
358 |
+
"""
|
359 |
+
Get kwargs for whisper model. Ensure that kwargs are valid.
|
360 |
+
|
361 |
+
Returns:
|
362 |
+
dict: Keyword arguments for whisper model.
|
363 |
+
"""
|
364 |
+
# _possible_kwargs = WhisperModel.transcribe.__code__.co_varnames
|
365 |
+
_possible_kwargs = signature(FasterWhisperModel.transcribe).parameters.keys()
|
366 |
+
|
367 |
+
whisper_kwargs = {k: v for k,
|
368 |
+
v in kwargs.items() if k in _possible_kwargs}
|
369 |
+
|
370 |
+
if (task := kwargs.get("task")):
|
371 |
+
whisper_kwargs["task"] = task
|
372 |
+
|
373 |
+
if (language := kwargs.get("language")):
|
374 |
+
language = FasterWhisperTranscriber.convert_to_language_code(language)
|
375 |
+
whisper_kwargs["language"] = language
|
376 |
+
|
377 |
+
return whisper_kwargs
|
378 |
+
|
379 |
+
@staticmethod
|
380 |
+
def convert_to_language_code(lang : str) -> str:
|
381 |
+
"""
|
382 |
+
Load whisper model.
|
383 |
+
|
384 |
+
Args:
|
385 |
+
lang (str): language as code or language name
|
386 |
+
|
387 |
+
Returns:
|
388 |
+
language (str) code of language
|
389 |
+
"""
|
390 |
+
|
391 |
+
# If the input is already in FASTER_WHISPER_LANGUAGE_CODES, return it directly
|
392 |
+
if lang in FASTER_WHISPER_LANGUAGE_CODES:
|
393 |
+
return lang
|
394 |
+
|
395 |
+
# Normalize the input to lowercase
|
396 |
+
lang = lang.lower()
|
397 |
+
|
398 |
+
# Check if the language name is in the TO_LANGUAGE_CODE mapping
|
399 |
+
if lang in TO_LANGUAGE_CODE:
|
400 |
+
return TO_LANGUAGE_CODE[lang]
|
401 |
+
|
402 |
+
# If the language is not recognized, raise a ValueError with the available options
|
403 |
+
available_codes = ', '.join(FASTER_WHISPER_LANGUAGE_CODES)
|
404 |
+
raise ValueError(f"Language '{lang}' is not a valid language code or name. "
|
405 |
+
f"Available language codes are: {available_codes}.")
|
406 |
+
|
407 |
+
def __repr__(self) -> str:
|
408 |
+
return f"FasterWhisperTranscriber(model_name={self.model_name}, model={self.model})"
|
409 |
+
|
410 |
+
|
411 |
+
|
412 |
+
def load_transcriber(model: str = "large-v3",
|
413 |
+
whisper_type: str = 'whisper',
|
414 |
+
download_root: str = WHISPER_DEFAULT_PATH,
|
415 |
+
device: Optional[Union[str, device]] = SCRAIBE_TORCH_DEVICE,
|
416 |
+
in_memory: bool = False,
|
417 |
+
*args, **kwargs
|
418 |
+
) -> Union[WhisperTranscriber, FasterWhisperTranscriber]:
|
419 |
+
"""
|
420 |
+
Load whisper model.
|
421 |
+
|
422 |
+
Args:
|
423 |
+
model (str): Whisper model. Available models include:
|
424 |
+
- 'tiny.en'
|
425 |
+
- 'tiny'
|
426 |
+
- 'base.en'
|
427 |
+
- 'base'
|
428 |
+
- 'small.en'
|
429 |
+
- 'small'
|
430 |
+
- 'medium.en'
|
431 |
+
- 'medium'
|
432 |
+
- 'large-v1'
|
433 |
+
- 'large-v2'
|
434 |
+
- 'large-v3'
|
435 |
+
- 'large'
|
436 |
+
whisper_type (str):
|
437 |
+
Type of whisper model to load. "whisper" or "faster-whisper".
|
438 |
+
download_root (str, optional): Path to download the model.
|
439 |
+
Defaults to WHISPER_DEFAULT_PATH.
|
440 |
+
device (Optional[Union[str, torch.device]], optional):
|
441 |
+
Device to load model on. Defaults to SCRAIBE_TORCH_DEVICE.
|
442 |
+
in_memory (bool, optional): Whether to load model in memory.
|
443 |
+
Defaults to False.
|
444 |
+
args: Additional arguments only to avoid errors.
|
445 |
+
kwargs: Additional keyword arguments only to avoid errors.
|
446 |
+
|
447 |
+
Returns:
|
448 |
+
Union[WhisperTranscriber, FasterWhisperTranscriber]:
|
449 |
+
One of the Whisper variants as Transcrbier object initialized with the specified model.
|
450 |
+
"""
|
451 |
+
if whisper_type.lower() == 'whisper':
|
452 |
+
_model = WhisperTranscriber.load_model(
|
453 |
+
model, download_root, device, in_memory, *args, **kwargs)
|
454 |
+
return _model
|
455 |
+
elif whisper_type.lower() == 'faster-whisper':
|
456 |
+
_model = FasterWhisperTranscriber.load_model(
|
457 |
+
model, download_root, device, *args, **kwargs)
|
458 |
+
return _model
|
459 |
+
else:
|
460 |
+
raise ValueError(f'Model type not recognized, exptected "whisper" '
|
461 |
+
f'or "faster-whisper", got {whisper_type}.')
|
scraibe/transcript_exporter.py
ADDED
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import time
|
3 |
+
from json.decoder import JSONDecodeError
|
4 |
+
|
5 |
+
from typing import Union
|
6 |
+
|
7 |
+
from .hallucinations import KNOWN_HALLUCINATIONS
|
8 |
+
|
9 |
+
ALPHABET = [*"abcdefghijklmnopqrstuvwxyz"]
|
10 |
+
|
11 |
+
|
12 |
+
class Transcript:
|
13 |
+
"""
|
14 |
+
Class for storing transcript data, including speaker information and text segments,
|
15 |
+
and exporting it to various file formats such as JSON, HTML, and LaTeX.
|
16 |
+
"""
|
17 |
+
|
18 |
+
def __init__(self, transcript: dict) -> None:
|
19 |
+
"""
|
20 |
+
Initializes the Transcript object with the given transcript data.
|
21 |
+
|
22 |
+
Args:
|
23 |
+
transcript (dict): A dictionary containing the formatted transcript string.
|
24 |
+
Keys should correspond to segment IDs, and values should
|
25 |
+
contain speaker and segment information.
|
26 |
+
"""
|
27 |
+
|
28 |
+
self.transcript = transcript
|
29 |
+
self._remove_hallucinations()
|
30 |
+
self.speakers = self._extract_speakers()
|
31 |
+
self.segments = self._extract_segments()
|
32 |
+
self.annotation = {}
|
33 |
+
|
34 |
+
def annotate(self, *args, **kwargs) -> dict:
|
35 |
+
"""
|
36 |
+
Annotates the transcript to associate specific names with speakers.
|
37 |
+
|
38 |
+
Args:
|
39 |
+
args (list): List of speaker names. These will be mapped sequentially to the speakers.
|
40 |
+
kwargs (dict): Dictionary with speaker names as keys and list of segments as values.
|
41 |
+
|
42 |
+
Returns:
|
43 |
+
dict: Dictionary with speaker names as keys and list of segments as values.
|
44 |
+
|
45 |
+
Raises:
|
46 |
+
ValueError: If the number of speaker names does not match the number
|
47 |
+
of speakers, or if an unknown speaker is found.
|
48 |
+
"""
|
49 |
+
|
50 |
+
annotations = {}
|
51 |
+
if args and len(args) != len(self.speakers):
|
52 |
+
raise ValueError(
|
53 |
+
"Number of speaker names does not match number of speakers")
|
54 |
+
|
55 |
+
if args:
|
56 |
+
for arg, speaker in zip(args, sorted(self.speakers)):
|
57 |
+
|
58 |
+
annotations[speaker] = arg
|
59 |
+
|
60 |
+
invalid_speakers = set(kwargs.keys()) - set(self.speakers)
|
61 |
+
if invalid_speakers:
|
62 |
+
raise ValueError(
|
63 |
+
f"These keys are not speakers: {', '.join(invalid_speakers)}")
|
64 |
+
|
65 |
+
annotations.update({key: kwargs[key]
|
66 |
+
for key in self.speakers if key in kwargs})
|
67 |
+
|
68 |
+
self.annotation = annotations
|
69 |
+
|
70 |
+
return self
|
71 |
+
|
72 |
+
def _remove_hallucinations(self) -> None:
|
73 |
+
"""
|
74 |
+
Removes all occurances of known hallucinations from all segments of the transcript.
|
75 |
+
Segments that are identical to empty strings afterwards are removed from the transcript.
|
76 |
+
"""
|
77 |
+
segments_to_drop = []
|
78 |
+
for id in self.transcript:
|
79 |
+
for snippet in KNOWN_HALLUCINATIONS:
|
80 |
+
self.transcript[id]['text'] = self.transcript[id]['text'].replace(
|
81 |
+
snippet, '')
|
82 |
+
if self.transcript[id]['text'] == '':
|
83 |
+
segments_to_drop.append(id)
|
84 |
+
|
85 |
+
for id in segments_to_drop:
|
86 |
+
del self.transcript[id]
|
87 |
+
|
88 |
+
def _extract_speakers(self) -> list:
|
89 |
+
"""
|
90 |
+
Extracts the unique speaker names from the transcript.
|
91 |
+
|
92 |
+
Returns:
|
93 |
+
list: List of unique speaker names in the transcript.
|
94 |
+
"""
|
95 |
+
|
96 |
+
return list(set([self.transcript[id]["speakers"] for id in self.transcript]))
|
97 |
+
|
98 |
+
def _extract_segments(self) -> list:
|
99 |
+
"""
|
100 |
+
Extracts all the text segments from the transcript.
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
list: List of segments, where each segment is represented
|
104 |
+
by the starting and ending times.
|
105 |
+
"""
|
106 |
+
return [self.transcript[id]["segments"] for id in self.transcript]
|
107 |
+
|
108 |
+
def __str__(self) -> str:
|
109 |
+
"""
|
110 |
+
Converts the transcript to a string representation.
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
str: String representation of the transcript, including speaker names and
|
114 |
+
time stamps for each segment.
|
115 |
+
"""
|
116 |
+
fstring = ""
|
117 |
+
|
118 |
+
for _id in self.transcript:
|
119 |
+
seq = self.transcript[_id]
|
120 |
+
|
121 |
+
if self.annotation:
|
122 |
+
speaker = self.annotation[seq["speakers"]]
|
123 |
+
else:
|
124 |
+
speaker = seq["speakers"]
|
125 |
+
|
126 |
+
segm = seq["segments"]
|
127 |
+
sseg = time.strftime("%H:%M:%S", time.gmtime(segm[0]))
|
128 |
+
eseg = time.strftime("%H:%M:%S", time.gmtime(segm[1]))
|
129 |
+
|
130 |
+
fstring += f"{speaker} ({sseg} ; {eseg}):\t{seq['text']}\n"
|
131 |
+
|
132 |
+
return fstring
|
133 |
+
|
134 |
+
def __repr__(self) -> str:
|
135 |
+
"""Return a string representation of the Transcript object.
|
136 |
+
|
137 |
+
Returns:
|
138 |
+
str: A string that provides an informative description of the object.
|
139 |
+
"""
|
140 |
+
return f"Transcript(speakers = {self.speakers},"\
|
141 |
+
f"segments = {self.segments}, annotation = {self.annotation})"
|
142 |
+
|
143 |
+
def get_dict(self) -> dict:
|
144 |
+
"""
|
145 |
+
Get transcript as dict
|
146 |
+
|
147 |
+
:return: transcript as dict
|
148 |
+
:rtype: dict
|
149 |
+
"""
|
150 |
+
|
151 |
+
return self.transcript
|
152 |
+
|
153 |
+
def get_json(self, *args, use_annotation: bool = True, **kwargs) -> str:
|
154 |
+
"""
|
155 |
+
Get transcript as json string
|
156 |
+
:return: transcript as json string
|
157 |
+
:rtype: str
|
158 |
+
"""
|
159 |
+
if "indent" not in kwargs:
|
160 |
+
kwargs["indent"] = 3
|
161 |
+
|
162 |
+
if use_annotation and self.annotation:
|
163 |
+
for _id in self.transcript:
|
164 |
+
seq = self.transcript[_id]
|
165 |
+
seq["speakers"] = self.annotation[seq["speakers"]]
|
166 |
+
|
167 |
+
return json.dumps(self.transcript, *args, **kwargs)
|
168 |
+
|
169 |
+
def get_html(self) -> str:
|
170 |
+
"""
|
171 |
+
Get transcript as html string
|
172 |
+
|
173 |
+
:return: transcript as html string
|
174 |
+
:rtype: str
|
175 |
+
"""
|
176 |
+
html = "<p>" + self.__str__().replace("\n", "<br>") + "</p>"
|
177 |
+
html = "<html><body>" + html + "</body></html>"
|
178 |
+
html = html.replace("\t", " ")
|
179 |
+
|
180 |
+
return html
|
181 |
+
|
182 |
+
def get_md(self) -> str:
|
183 |
+
"""Get transcript as Markdown string, using HTML formatting.
|
184 |
+
|
185 |
+
Returns:
|
186 |
+
str: Transcript as a Markdown string.
|
187 |
+
"""
|
188 |
+
return self.get_html()
|
189 |
+
|
190 |
+
def get_tex(self) -> str:
|
191 |
+
"""Get transcript as LaTeX string. If no annotations are present, the speakers will
|
192 |
+
be annotated with the first letters of the alphabet.
|
193 |
+
|
194 |
+
Returns:
|
195 |
+
str: Transcript as LaTeX string.
|
196 |
+
"""
|
197 |
+
if not self.annotation:
|
198 |
+
|
199 |
+
self.annotate(*ALPHABET[:len(self.speakers)])
|
200 |
+
|
201 |
+
fstring = "\\begin{drama}"
|
202 |
+
|
203 |
+
for speaker in self.speakers:
|
204 |
+
|
205 |
+
fstring += "\n\t\\Character{" + str(self.annotation[speaker]) + "}" \
|
206 |
+
"{" + str(self.annotation[speaker]) + "}"
|
207 |
+
|
208 |
+
for id in self.transcript:
|
209 |
+
seq = self.transcript[id]
|
210 |
+
speaker = self.annotation[seq["speakers"]]
|
211 |
+
fstring += f"\n\\{speaker}speaks:\n{seq['text']}"
|
212 |
+
|
213 |
+
fstring += "\n\\end{drama}"
|
214 |
+
|
215 |
+
return fstring
|
216 |
+
|
217 |
+
def to_json(self, path, *args, **kwargs) -> None:
|
218 |
+
"""Save transcript as json file
|
219 |
+
|
220 |
+
Args:
|
221 |
+
path (str): path to save file
|
222 |
+
"""
|
223 |
+
with open(path, "w") as f:
|
224 |
+
json.dump(self.transcript, f, *args, **kwargs)
|
225 |
+
|
226 |
+
def to_txt(self, path: str) -> None:
|
227 |
+
"""Save transcript as a LaTeX file (placeholder function, implementation needed).
|
228 |
+
|
229 |
+
Args:
|
230 |
+
path (str): Path to save the LaTeX file.
|
231 |
+
"""
|
232 |
+
|
233 |
+
with open(path, "w") as f:
|
234 |
+
f.write(self.__str__())
|
235 |
+
|
236 |
+
def to_md(self, path: str) -> None:
|
237 |
+
"""Get transcript as Markdown string, using HTML formatting.
|
238 |
+
|
239 |
+
Returns:
|
240 |
+
str: Transcript as a Markdown string.
|
241 |
+
"""
|
242 |
+
return self.to_html(path)
|
243 |
+
|
244 |
+
def to_html(self, path: str) -> None:
|
245 |
+
"""
|
246 |
+
Save transcript as html file
|
247 |
+
|
248 |
+
:param path: path to save file
|
249 |
+
:type path: str
|
250 |
+
"""
|
251 |
+
|
252 |
+
with open(path, "w") as file:
|
253 |
+
file.write(self.get_html())
|
254 |
+
|
255 |
+
def to_tex(self, path: str) -> None:
|
256 |
+
"""Save transcript as a LaTeX file (placeholder function, implementation needed).
|
257 |
+
|
258 |
+
Args:
|
259 |
+
path (str): Path to save the LaTeX file.
|
260 |
+
"""
|
261 |
+
pass
|
262 |
+
|
263 |
+
def to_pdf(self, path: str) -> None:
|
264 |
+
"""Save transcript as a PDF file (placeholder function, implementation needed).
|
265 |
+
|
266 |
+
Args:
|
267 |
+
path (str): Path to save the PDF file.
|
268 |
+
"""
|
269 |
+
pass
|
270 |
+
|
271 |
+
def save(self, path: str, *args, **kwargs) -> None:
|
272 |
+
"""Save transcript to file with the given path and file format.
|
273 |
+
|
274 |
+
This method can save the transcript in various formats including JSON, TXT,
|
275 |
+
MD, HTML, TEX, and PDF. The file format is determined by the extension of
|
276 |
+
the path.
|
277 |
+
|
278 |
+
Args:
|
279 |
+
path (str): Path to save the file, including the desired file extension.
|
280 |
+
*args: Additional positional arguments to be passed to the specific save methods.
|
281 |
+
**kwargs: Additional keyword arguments to be passed to the specific save methods.
|
282 |
+
|
283 |
+
Raises:
|
284 |
+
ValueError: If the file format specified in the path is unknown.
|
285 |
+
"""
|
286 |
+
|
287 |
+
if path.endswith(".json"):
|
288 |
+
self.to_json(path, *args, **kwargs)
|
289 |
+
elif path.endswith(".txt"):
|
290 |
+
self.to_txt(path, *args, **kwargs)
|
291 |
+
elif path.endswith(".md"):
|
292 |
+
self.to_md(path, *args, **kwargs)
|
293 |
+
elif path.endswith(".html"):
|
294 |
+
self.to_html(path, *args, **kwargs)
|
295 |
+
elif path.endswith(".tex"):
|
296 |
+
self.to_tex(path, *args, **kwargs)
|
297 |
+
elif path.endswith(".pdf"):
|
298 |
+
self.to_pdf(path, *args, **kwargs)
|
299 |
+
else:
|
300 |
+
raise ValueError("Unknown file format")
|
301 |
+
|
302 |
+
@classmethod
|
303 |
+
def from_json(cls, _json: Union[dict, str]) -> "Transcript":
|
304 |
+
"""Load transcript from json file
|
305 |
+
|
306 |
+
Args:
|
307 |
+
path (str): path to json file
|
308 |
+
|
309 |
+
Returns:
|
310 |
+
Transcript: Transcript object
|
311 |
+
"""
|
312 |
+
if isinstance(_json, dict):
|
313 |
+
return cls(_json)
|
314 |
+
else:
|
315 |
+
try:
|
316 |
+
transcript = json.loads(_json)
|
317 |
+
except (TypeError, JSONDecodeError):
|
318 |
+
with open(_json, "r") as f:
|
319 |
+
transcript = json.load(f)
|
320 |
+
|
321 |
+
return cls(transcript)
|
source/conf.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Configuration file for the Sphinx documentation builder.
|
2 |
+
#
|
3 |
+
# This file only contains a selection of the most common options. For a full
|
4 |
+
# list see the documentation:
|
5 |
+
# https://www.sphinx-doc.org/en/master/usage/configuration.html
|
6 |
+
|
7 |
+
# -- Path setup --------------------------------------------------------------
|
8 |
+
|
9 |
+
# If extensions (or modules to document with autodoc) are in another directory,
|
10 |
+
# add these directories to sys.path here. If the directory is relative to the
|
11 |
+
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
12 |
+
#
|
13 |
+
import os
|
14 |
+
import sys
|
15 |
+
sys.path.insert(0, os.path.abspath('../'))
|
16 |
+
|
17 |
+
|
18 |
+
# -- Project information -----------------------------------------------------
|
19 |
+
|
20 |
+
project = 'ScrAIbe: Streamlined Conversation Recording with Automated Intelligence Based Environment'
|
21 |
+
copyright = '2023, Jacob Schmieder'
|
22 |
+
author = 'Jacob Schmieder'
|
23 |
+
|
24 |
+
# The full version, including alpha/beta/rc tags
|
25 |
+
release = '0.1.1'
|
26 |
+
|
27 |
+
|
28 |
+
# -- General configuration ---------------------------------------------------
|
29 |
+
|
30 |
+
# Add any Sphinx extension module names here, as strings. They can be
|
31 |
+
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
32 |
+
# ones.
|
33 |
+
extensions = ['sphinx.ext.autodoc',
|
34 |
+
'sphinx.ext.doctest',
|
35 |
+
'sphinx.ext.intersphinx',
|
36 |
+
'sphinx.ext.todo',
|
37 |
+
'sphinx.ext.coverage',
|
38 |
+
'sphinx.ext.mathjax',
|
39 |
+
'sphinx.ext.ifconfig',
|
40 |
+
'sphinx.ext.viewcode',
|
41 |
+
'sphinx.ext.githubpages',
|
42 |
+
'sphinx.ext.napoleon',
|
43 |
+
'myst_parser']
|
44 |
+
|
45 |
+
# Napoleon settings
|
46 |
+
napoleon_google_docstring = True
|
47 |
+
napoleon_numpy_docstring = True
|
48 |
+
napoleon_include_init_with_doc = True
|
49 |
+
napoleon_include_private_with_doc = True
|
50 |
+
napoleon_include_special_with_doc = True
|
51 |
+
napoleon_use_admonition_for_examples = False
|
52 |
+
napoleon_use_admonition_for_notes = False
|
53 |
+
napoleon_use_admonition_for_references = False
|
54 |
+
napoleon_use_ivar = False
|
55 |
+
napoleon_use_param = True
|
56 |
+
napoleon_use_rtype = True
|
57 |
+
|
58 |
+
# Add any paths that contain templates here, relative to this directory.
|
59 |
+
templates_path = ['_templates']
|
60 |
+
|
61 |
+
# List of patterns, relative to source directory, that match files and
|
62 |
+
# directories to ignore when looking for source files.
|
63 |
+
# This pattern also affects html_static_path and html_extra_path.
|
64 |
+
exclude_patterns = []
|
65 |
+
|
66 |
+
# Add source file parsers
|
67 |
+
source_suffix = {
|
68 |
+
'.rst': 'restructuredtext',
|
69 |
+
'.txt': 'markdown',
|
70 |
+
'.md': 'markdown',
|
71 |
+
}
|
72 |
+
|
73 |
+
|
74 |
+
# -- Options for HTML output -------------------------------------------------
|
75 |
+
|
76 |
+
# The theme to use for HTML and HTML Help pages. See the documentation for
|
77 |
+
# a list of builtin themes.
|
78 |
+
#
|
79 |
+
html_theme = 'sphinx_rtd_theme'
|
80 |
+
|
81 |
+
# Add any paths that contain custom static files (such as style sheets) here,
|
82 |
+
# relative to this directory. They are copied after the builtin static files,
|
83 |
+
# so a file named "default.css" will overwrite the builtin "default.css".
|
84 |
+
html_static_path = ['_static']
|
source/index.rst
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Welcome to ScrAIbe: Streamlined Conversation Recording with Automated Intelligence Based Environment's documentation!
|
2 |
+
=====================================================================================================================
|
3 |
+
|
4 |
+
.. automodule:: scraibe
|
5 |
+
:members:
|
6 |
+
|
7 |
+
.. toctree::
|
8 |
+
:maxdepth: 2
|
9 |
+
:caption: Contents:
|
10 |
+
|
11 |
+
../README.md
|
12 |
+
|
13 |
+
modules
|
14 |
+
|
15 |
+
|
16 |
+
Indices and tables
|
17 |
+
==================
|
18 |
+
|
19 |
+
* :ref:`genindex`
|
20 |
+
* :ref:`modindex`
|
21 |
+
* :ref:`search`
|
source/modules.rst
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
scraibe
|
2 |
+
=======
|
3 |
+
|
4 |
+
.. toctree::
|
5 |
+
:maxdepth: 4
|
6 |
+
|
7 |
+
scraibe
|
tests/audio_test_1.mp4
ADDED
Binary file (768 kB). View file
|
|
tests/audio_test_2.mp4
ADDED
Binary file (227 kB). View file
|
|
tests/test_audio.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from scraibe.audio import AudioProcessor
|
3 |
+
import torch
|
4 |
+
|
5 |
+
|
6 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
+
TEST_WAVEFORM = torch.sin(torch.randn(160000)).to(DEVICE)
|
8 |
+
TEST_SR = 16000
|
9 |
+
SAMPLE_RATE = 16000
|
10 |
+
NORMALIZATION_FACTOR = 32768
|
11 |
+
|
12 |
+
|
13 |
+
@pytest.fixture
|
14 |
+
def probe_audio_processor():
|
15 |
+
"""Fixture for creating an instance of the AudioProcessor class with test waveform and sample rate.
|
16 |
+
|
17 |
+
This fixture is used to create an instance of the AudioProcessor class with a predfined test waveform and sample rate (TEST_SR). It returns the instantiated AudioProcessor , which can bes used as a
|
18 |
+
dependency in other test functions.
|
19 |
+
|
20 |
+
|
21 |
+
Returns:
|
22 |
+
AudioProcessor (obj): An instance of the AudioProcessor class with the test waveform and sample rate.
|
23 |
+
"""
|
24 |
+
return AudioProcessor(TEST_WAVEFORM, TEST_SR)
|
25 |
+
|
26 |
+
|
27 |
+
def test_AudioProcessor_init(probe_audio_processor):
|
28 |
+
"""
|
29 |
+
Test the initialization of the AudioProcessor class.
|
30 |
+
|
31 |
+
This test verifies that the AUdioProcessor class is correctly initialized with the provided waveform and sample rate. It checks whether the instantiated AhdioProcessor object has the correct attributes
|
32 |
+
and whether the waveform and sample rate match the expected values.
|
33 |
+
|
34 |
+
Args:
|
35 |
+
probe_audio_processor (obj): An instance of the AudioProcessor class to be tested.
|
36 |
+
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
None
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
|
44 |
+
"""
|
45 |
+
assert isinstance(probe_audio_processor, AudioProcessor)
|
46 |
+
assert probe_audio_processor.waveform.device == TEST_WAVEFORM.device
|
47 |
+
assert torch.equal(probe_audio_processor.waveform, TEST_WAVEFORM)
|
48 |
+
assert probe_audio_processor.sr == TEST_SR
|
49 |
+
|
50 |
+
|
51 |
+
def test_cut(probe_audio_processor):
|
52 |
+
"""Test the cut function of the AudioProcessor class.
|
53 |
+
|
54 |
+
This test verifies that the cut function correctly extracts a segment of audio data from
|
55 |
+
the waveform, given start and end indices. It checks whether the size of the extracted segment matches
|
56 |
+
the expected size based on the provided start and end indices and the sample rate.
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
None
|
60 |
+
|
61 |
+
|
62 |
+
"""
|
63 |
+
|
64 |
+
start = 4
|
65 |
+
end = 7
|
66 |
+
trimmed_waveform = probe_audio_processor.cut(start, end)
|
67 |
+
expected_size = int((end - start) * TEST_SR)
|
68 |
+
real_size = trimmed_waveform.size(0)
|
69 |
+
assert real_size == expected_size
|
70 |
+
# assert AudioProcessor(TEST_WAVEFORM, TEST_SR).cut(start, end).size() == int((end - start) * TEST_SR)
|
71 |
+
|
72 |
+
|
73 |
+
def test_audio_processor_invalid_sr():
|
74 |
+
"""Test the behavior of AudioProcessor when an invalid smaple rate is provided.
|
75 |
+
|
76 |
+
This test verifies that the AudioProcessor constructor raises a ValueError when an invalid sample rate is provided. It uses the pytest.raises context manager to check if the ValueError is raised when initializing an
|
77 |
+
AudioProcessor object with an invalid sample rate.
|
78 |
+
|
79 |
+
Returns:
|
80 |
+
None
|
81 |
+
"""
|
82 |
+
with pytest.raises(ValueError):
|
83 |
+
AudioProcessor(TEST_WAVEFORM, [44100, 48000])
|
84 |
+
|
85 |
+
|
86 |
+
def test_audio_processor_SAMPLE_RATE():
|
87 |
+
"""Test the default sample rate of the AudioProcessor class.
|
88 |
+
|
89 |
+
This test verifies that the default sample rate of the AudioProcessor class matches the expected value defined by the constant SAMPLE_RATE. It instantiates an AudioProcessor object with a test waveform
|
90 |
+
and checks whether the sample rate attribute (sr) of the AudioProcessor object equals the predefined constant SAMPLE_RATE.
|
91 |
+
|
92 |
+
Returns:
|
93 |
+
None
|
94 |
+
"""
|
95 |
+
probe_audio_processor = AudioProcessor(TEST_WAVEFORM)
|
96 |
+
assert probe_audio_processor.sr == SAMPLE_RATE
|
tests/test_autotranscript.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from scraibe import Scraibe, Diariser, Transcriber, Transcript
|
3 |
+
import os
|
4 |
+
|
5 |
+
|
6 |
+
@pytest.fixture
|
7 |
+
def create_scraibe_instance():
|
8 |
+
if "HF_TOKEN" in os.environ:
|
9 |
+
return Scraibe(use_auth_token=os.environ["HF_TOKEN"], whisper_model= "tiny")
|
10 |
+
else:
|
11 |
+
return Scraibe()
|
12 |
+
|
13 |
+
|
14 |
+
def test_scraibe_init(create_scraibe_instance):
|
15 |
+
model = create_scraibe_instance
|
16 |
+
assert isinstance(model.transcriber, Transcriber)
|
17 |
+
assert isinstance(model.diariser, Diariser)
|
18 |
+
|
19 |
+
|
20 |
+
def test_scraibe_autotranscribe(create_scraibe_instance):
|
21 |
+
model = create_scraibe_instance
|
22 |
+
transcript = model.autotranscribe('tests/audio_test_2.mp4')
|
23 |
+
assert isinstance(transcript, Transcript)
|
24 |
+
|
25 |
+
|
26 |
+
def test_scraibe_diarization(create_scraibe_instance):
|
27 |
+
model = create_scraibe_instance
|
28 |
+
diarisation_result = model.diarization('tests/audio_test_2.mp4')
|
29 |
+
assert isinstance(diarisation_result, dict)
|
30 |
+
|
31 |
+
|
32 |
+
def test_scraibe_transcribe(create_scraibe_instance):
|
33 |
+
model = create_scraibe_instance
|
34 |
+
transcription_result = model.transcribe('tests/audio_test_2.mp4')
|
35 |
+
assert isinstance(transcription_result, str)
|
36 |
+
|
37 |
+
|
38 |
+
""" def test_remove_audio_file(create_scraibe_instance):
|
39 |
+
model = create_scraibe_instance
|
40 |
+
with pytest.raises(ValueError):
|
41 |
+
model.remove_audio_file("non_existing_audio_file")
|
42 |
+
|
43 |
+
model.remove_audio_file("audio_test_2.mp4")
|
44 |
+
assert not os.path.exists("audio_test_2.mp4") """
|
45 |
+
|
46 |
+
|
47 |
+
""" def test_get_audio_file(create_scraibe_instance):
|
48 |
+
model = create_scraibe_instance
|
49 |
+
audio_file = os.path.exist("audio_test_2.mp4")
|
50 |
+
assert isinstance(audio_file, AudioProcessor)
|
51 |
+
assert isinstance(audio_file.waveform, torch.Tensor)
|
52 |
+
assert isinstance(audio_file.sr, torch.Tensor) """
|
tests/test_diarisation.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from scraibe import Diariser
|
3 |
+
|
4 |
+
|
5 |
+
@pytest.fixture
|
6 |
+
def diariser_instance():
|
7 |
+
"""Fixture for creating an instance of the Diariser class with mocked token.
|
8 |
+
|
9 |
+
This fixture is used to create an instance of the the Diariser class with a mocked token returned by the _get_token method. It patches the _get_token method of the Diariser class
|
10 |
+
using unit.test.mock.patch.object, ensuring that it returns a predetrmined value ('personal Hugging-Face token'). The mocked Diariser object is retunrned and can be used as a dependency in otehr tests.
|
11 |
+
|
12 |
+
Returns:
|
13 |
+
Diariser(Obj): An instance of the Diariser class with a mocked token.
|
14 |
+
"""
|
15 |
+
# with mock.patch.object(Diariser, '_get_token', return_value = 'HF_TOKEN' ):
|
16 |
+
return Diariser('pyannote')
|
17 |
+
|
18 |
+
|
19 |
+
def test_Diariser_init(diariser_instance):
|
20 |
+
"""Test the initialization of the Diariser class.
|
21 |
+
|
22 |
+
This test verifies that the Diariser class is correctly initialized with the specified model.
|
23 |
+
It checks whether the 'model' attribute of the instantiated Diariser object equals 'pyannote'.
|
24 |
+
|
25 |
+
|
26 |
+
Args:
|
27 |
+
diariser_instance (obj): instance of the Diariser class
|
28 |
+
|
29 |
+
Returns:
|
30 |
+
None
|
31 |
+
"""
|
32 |
+
assert diariser_instance.model == 'pyannote'
|
tests/test_transcriber.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from scraibe import (Transcriber, WhisperTranscriber,
|
3 |
+
FasterWhisperTranscriber, load_transcriber)
|
4 |
+
import torch
|
5 |
+
|
6 |
+
|
7 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
8 |
+
TEST_WAVEFORM = "Hello World"
|
9 |
+
|
10 |
+
"""
|
11 |
+
@pytest.mark.parametrize("audio_file, expected_transcription",[("path_to_test_audiofile", "test_transcription")] )
|
12 |
+
@patch("scraibe.Transcriber.load_model")
|
13 |
+
|
14 |
+
def test_transcriber(mock_load_model, audio_file, expected_transcription):
|
15 |
+
|
16 |
+
|
17 |
+
Args:
|
18 |
+
mock_load_model (_type_): _description_
|
19 |
+
audio_file (_type_): _description_
|
20 |
+
expected_transcription (_type_): _description_
|
21 |
+
|
22 |
+
mock_model = mock_load_model.return_value
|
23 |
+
mock_model.transcribe.return_value ={"text": expected_transcription}
|
24 |
+
|
25 |
+
transcriber = Transcriber.load_model(model="medium")
|
26 |
+
|
27 |
+
transcription_result = transcriber.transcribe(audio=audio_file)
|
28 |
+
|
29 |
+
assert transcription_result == expected_transcription """
|
30 |
+
|
31 |
+
|
32 |
+
@pytest.fixture
|
33 |
+
def whisper_instance():
|
34 |
+
return load_transcriber('tiny', whisper_type='whisper')
|
35 |
+
|
36 |
+
|
37 |
+
@pytest.fixture
|
38 |
+
def faster_whisper_instance():
|
39 |
+
return load_transcriber('tiny', whisper_type='faster-whisper')
|
40 |
+
|
41 |
+
|
42 |
+
def test_whisper_base_initialization(whisper_instance):
|
43 |
+
assert isinstance(whisper_instance, Transcriber)
|
44 |
+
|
45 |
+
|
46 |
+
def test_faster_whisper_base_initialization(faster_whisper_instance):
|
47 |
+
assert isinstance(faster_whisper_instance, Transcriber)
|
48 |
+
|
49 |
+
|
50 |
+
def test_whisper_transcriber_initialization(whisper_instance):
|
51 |
+
assert isinstance(whisper_instance, WhisperTranscriber)
|
52 |
+
|
53 |
+
|
54 |
+
def test_faster_whisper_transcriber_initialization(faster_whisper_instance):
|
55 |
+
assert isinstance(faster_whisper_instance, FasterWhisperTranscriber)
|
56 |
+
|
57 |
+
|
58 |
+
def test_wrong_transcriber_initialization():
|
59 |
+
with pytest.raises(ValueError):
|
60 |
+
load_transcriber('tiny', whisper_type='wrong_whisper')
|
61 |
+
|
62 |
+
|
63 |
+
def test_get_whisper_kwargs():
|
64 |
+
kwargs = {"arg1": 1, "arg3": 3}
|
65 |
+
valid_kwargs = Transcriber._get_whisper_kwargs(**kwargs)
|
66 |
+
assert not valid_kwargs == {"arg1": 1, "arg3": 3}
|
67 |
+
|
68 |
+
|
69 |
+
def test_whisper_transcribe(whisper_instance):
|
70 |
+
model = whisper_instance
|
71 |
+
# mocker.patch.object(transcriber_instance.model, 'transcribe', return_value={'Hello, World !'} )
|
72 |
+
transcript = model.transcribe('tests/audio_test_2.mp4')
|
73 |
+
assert isinstance(transcript, str)
|
74 |
+
|
75 |
+
|
76 |
+
def test_faster_whisper_transcribe(faster_whisper_instance):
|
77 |
+
model = faster_whisper_instance
|
78 |
+
# mocker.patch.object(transcriber_instance.model, 'transcribe', return_value={'Hello, World !'} )
|
79 |
+
transcript = model.transcribe('tests/audio_test_2.mp4')
|
80 |
+
assert isinstance(transcript, str)
|