@@ -0,0 +1,39 @@
|
|||||||
|
# This workflow will upload a Python Package using Twine when a release is created
|
||||||
|
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
|
||||||
|
|
||||||
|
# This workflow uses actions that are not certified by GitHub.
|
||||||
|
# They are provided by a third-party and are governed by
|
||||||
|
# separate terms of service, privacy policy, and support
|
||||||
|
# documentation.
|
||||||
|
|
||||||
|
name: Upload Python Package
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [published]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v3
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install build
|
||||||
|
- name: Build package
|
||||||
|
run: python -m build
|
||||||
|
- name: Publish package
|
||||||
|
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
|
||||||
|
with:
|
||||||
|
user: __token__
|
||||||
|
password: ${{ secrets.PYPI_API_TOKEN }}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#pytorch Image
|
||||||
|
FROM pytorch/pytorch:1.11.0-cuda11.3-cudnn8-runtime
|
||||||
|
# Install dependencies
|
||||||
|
WORKDIR /app
|
||||||
|
ARG hf_token
|
||||||
|
#Enviorment Dependncies
|
||||||
|
ENV TRANSFORMERS_CACHE /app/models
|
||||||
|
ENV HF_HOME /app/models
|
||||||
|
ENV AUTOT_CACHE /app/models
|
||||||
|
ENV PYANNOTE_CACHE /app/models/pyannote
|
||||||
|
#Copy all necessary files
|
||||||
|
COPY requirements.txt /app/requirements.txt
|
||||||
|
COPY scraibe /app/Scraibe
|
||||||
|
COPY setup.py /app/setup.py
|
||||||
|
#Installing all necessary Dependencies and Running the Application with a personalised Hugging-Face-Token
|
||||||
|
RUN conda install pip
|
||||||
|
RUN conda install -y ffmpeg
|
||||||
|
RUN conda install -c conda-forge libsndfile
|
||||||
|
RUN pip install torchaudio==0.11.0+cu113 -f https://download.pytorch.org/whl/torch_stable.html
|
||||||
|
RUN pip install /app/
|
||||||
|
RUN pip install markupsafe==2.0.1 --force-reinstall
|
||||||
|
RUN Scraibe --hf_token $hf_token
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 7860
|
||||||
|
# Run the application
|
||||||
|
ENTRYPOINT ["scraibe"]
|
||||||
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 901 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
@@ -1 +1,199 @@
|
|||||||
# transcriptor
|
|
||||||
|
# `ScrAIbe: Streamlined Conversation Recording with Automated Intelligence Based Environment`
|
||||||
|
|
||||||
|
`ScrAIbe` is a state-of-the-art, [PyTorch](https://pytorch.org/) based multilingual speech-to-text framework to generate fully automated transcriptions.
|
||||||
|
|
||||||
|
Beyond transcription, ScrAIbe supports advanced functions, such as speaker diarization and speaker recognition.
|
||||||
|
|
||||||
|
Designed as a comprehensive AI toolkit, it uses multiple AI models:
|
||||||
|
|
||||||
|
- [whisper](https://github.com/openai/whisper): A general-purpose speech recognition model.
|
||||||
|
- [payannote-audio](https://github.com/pyannote/pyannote-audio): An open-source toolkit for speaker diarization.
|
||||||
|
|
||||||
|
The framework utilizes a PyanNet-inspired pipeline, with the `Pyannote` library for speaker diarization and `VoxCeleb` for speaker embedding.
|
||||||
|
|
||||||
|
During post-diarization, each audio segment is processed by the OpenAI `Whisper` model, in a transformer encoder-decoder structure. Initially, a CNN mitigates noise and enhances speech. Before transcription, `VoxLingua` identifies the language segment, facilitating Whisper's role in both transcription and text translation.
|
||||||
|
|
||||||
|
The following graphic illustrates the whole pipeline:
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
## Install `ScrAIbe` :
|
||||||
|
|
||||||
|
The following command will pull and install the latest commit from this repository, along with its Python dependencies.
|
||||||
|
|
||||||
|
pip install scraibe
|
||||||
|
|
||||||
|
- **Python version**: Python 3.8
|
||||||
|
- **PyTorch version**: Python 1.11.0
|
||||||
|
- **CUDA version**: Cuda-toolkit 11.3.1
|
||||||
|
|
||||||
|
|
||||||
|
Important: For the `Pyannote` model, you need to be granted access to Hugging Face.
|
||||||
|
Check the [Pyannote model page](https://huggingface.co/pyannote/speaker-diarization) to get access to the model.
|
||||||
|
|
||||||
|
Additionally, you need to generate a [Hugging Face token](https://huggingface.co/docs/hub/security-tokens).
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
We've developed ScrAIbe with several access points to cater to diverse user needs.
|
||||||
|
|
||||||
|
### Python usage
|
||||||
|
|
||||||
|
It enables full control over the functionalities as well as process customization.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from scraibe import Scraibe
|
||||||
|
|
||||||
|
model = Scraibe(use_auth_token = "hf_yourhftoken")
|
||||||
|
|
||||||
|
text = model.autotranscribe("audio.wav")
|
||||||
|
|
||||||
|
print(f"Transcription: \n{text}")
|
||||||
|
```
|
||||||
|
The `Scraibe` Class is taking care of the models being properly loaded. Therefore, you can choose the other [whisper](https://github.com/openai/whisper/blob/main/model-card.md) models using the `whisper_model` keyword.
|
||||||
|
You can also change the `pyannote` diarization model using the `dia_model` keyword.
|
||||||
|
|
||||||
|
|
||||||
|
As input, `autoranscribe` accepts every format which is compatible with [ffmgeg](https://ffmpeg.org/ffmpeg-formats.html). Examples therefore are `.mp4 .mp3 .wav .ogg .flac` and many more.
|
||||||
|
|
||||||
|
To further control the pipeline of `ScrAIbe` you can parse almost any keyword you also cloud parsed towards `whisper` or `pyannote` if you need more option, try to check out the documentations tows two Frameworks, you might have a good chance that these keywords will work here as well.
|
||||||
|
Here's are some examples regarding the `diarization` (which relies on the `pyannote` pipeline):
|
||||||
|
|
||||||
|
- `num_speakers` Number of speakers in the audio file
|
||||||
|
- `min_speakers` Minimal Number of speakers in the audio file
|
||||||
|
- `max_speakers` maximal Number of speakers in the audio file
|
||||||
|
|
||||||
|
Then there are arguments about the transcription process, which uses the "whisper" model.
|
||||||
|
|
||||||
|
- `language` Specify the language ([list to supported languages](https://github.com/openai/whisper/blob/main/language-breakdown.svg))
|
||||||
|
- `task` can be just `transcribe` or `translate`. If `translate` is selected, the transcribed audio will be translated to English.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```
|
||||||
|
text = model.autotranscribe("audio.wav", language="german", num_speakers = 2)
|
||||||
|
```
|
||||||
|
|
||||||
|
`Scraibe` also contains the option to just do a transcription
|
||||||
|
```python
|
||||||
|
transcription = model.transcribe("audio.wav")
|
||||||
|
```
|
||||||
|
or just do a diarization:
|
||||||
|
|
||||||
|
```python
|
||||||
|
diarization = model.diarize("audio.wav")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Command-line usage
|
||||||
|
|
||||||
|
Next to the Pyhton interface, you can also run ScrAIbe using the command-line interface:
|
||||||
|
|
||||||
|
scraibe -f "audio.wav" --hf-token "hf_yourhftoken" --language "german" --num_speakers 2
|
||||||
|
|
||||||
|
For the full list of options, run:
|
||||||
|
|
||||||
|
scraibe -h
|
||||||
|
|
||||||
|
### Gradio App
|
||||||
|
|
||||||
|
The Gradio App is a user-friendly interface for ScrAIbe. It enables you to run the model without any coding knowledge. Therefore, you can run the app in your browser and upload your audio file, or you can make the Framework avail on your network and run it on your local machine.
|
||||||
|
|
||||||
|
#### Running the Gradio App on your local machine
|
||||||
|
|
||||||
|
To run the Gradio App on your local machine, just use the following command:
|
||||||
|
|
||||||
|
```
|
||||||
|
scraibe --start_server --port 7860 --hf_token hf_yourhftoken
|
||||||
|
```
|
||||||
|
|
||||||
|
- `--start_server`: Command to start the Gradio App.
|
||||||
|
- `--port`: Flag for connecting the container internal port to the port on your local machine.
|
||||||
|
- `--hf_token`: Flag for entering your personal HuggingFace token in the container.
|
||||||
|
|
||||||
|
When the app is running, it will show you at which address you can access it.
|
||||||
|
The default address is: http://127.0.0.1:7860 or http://0.0.0.0:7860
|
||||||
|
|
||||||
|
After the app is running, you can upload your audio file and select the desired options.
|
||||||
|
An example is shown below:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
|
### Running a Docker container
|
||||||
|
|
||||||
|
Another option to run ScrAIbe is to use a Docker container. This option is especially useful if you want to run the model on a server or if you would like to use the GPU without dealing with CUDA.
|
||||||
|
After you have installed Docker, you can execute the following commands in the terminal.
|
||||||
|
|
||||||
|
First, you need to build the Docker image. Therefore, you need to enter your HuggingFace token and the image name.
|
||||||
|
|
||||||
|
```
|
||||||
|
docker build . --build-arg="hf_token=[enter your HuggingFace token] " -t scraibe
|
||||||
|
```
|
||||||
|
|
||||||
|
After the image is built, you can run the container with the following command:
|
||||||
|
|
||||||
|
```
|
||||||
|
sudo docker run -it -p 7860:7860 --name [container name][image name] --hf_token [enter your HuggingFace token] --start_server
|
||||||
|
|
||||||
|
```
|
||||||
|
- `-p`: Flag for connecting the container internal port to the port on your local machine.
|
||||||
|
- `--hf_token`: Flag for entering your personal HuggingFace token in the container.
|
||||||
|
- `--start_server`: Command to start the Gradio App.
|
||||||
|
|
||||||
|
Inside the container, the `cli` is used. Therefore, you can use the same commands as in the command-line interface.
|
||||||
|
|
||||||
|
#### Enabling GPU usage
|
||||||
|
|
||||||
|
To use the GPU, ensure your Docker installation supports GPU usage.
|
||||||
|
For further information, check: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker
|
||||||
|
To enable GPU usage, you need to add the following flag to the `docker run` command:
|
||||||
|
|
||||||
|
```
|
||||||
|
docker run -it -p 7860:7860 --gpus 'all,capabilities=utility' --name [container name][image name] --hf_token [enter your HuggingFace token] --start_server
|
||||||
|
```
|
||||||
|
|
||||||
|
For further guidance, check: https://blog.roboflow.com/use-the-gpu-in-docker/
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
For further insights, check the [documentation page]().
|
||||||
|
|
||||||
|
## Contributions
|
||||||
|
|
||||||
|
We are happy to have any interest in contributing and about feedback: In order to do that, create an issue with your feedback or feel free to contact us.
|
||||||
|
|
||||||
|
## Roadmap
|
||||||
|
|
||||||
|
The following milestones are planned for further releases of ScrAIbe:
|
||||||
|
|
||||||
|
- Model quantization
|
||||||
|
Quantization to empower memory and computational efficiency.
|
||||||
|
|
||||||
|
- Model fine-tuning
|
||||||
|
In order to be able to cover a variety of linguistic phenomena.
|
||||||
|
|
||||||
|
For example, currently ScrAIbe is able to transcribe word by word, but ignores filler words or speech pauses.
|
||||||
|
These phenomena can be addressed by fine-tuning with the corresponding data.
|
||||||
|
|
||||||
|
- Implementation of LLMs
|
||||||
|
One example is the implementation of a summarization or extraction model, which enables ScrAIbe to automatically summarize or retrieve the key information out of a generated transcription, which could be the minutes of a meeting.
|
||||||
|
|
||||||
|
- Executable for Windows
|
||||||
|
|
||||||
|
## Contact
|
||||||
|
|
||||||
|
For queries contact [Jacob Schmieder](Jacob.Schmieder@dbfz.de)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
ScrAIbe is licensed under GNU General Public License.
|
||||||
|
|
||||||
|
## Acknowledgments
|
||||||
|
|
||||||
|
Special thanks go to the KIDA project and the BMEL (Bundesministerium für Ernährung und Landwirtschaft), especially to the AI Consultancy Team.
|
||||||
|
|
||||||
|
   
|
||||||
|
|
||||||
|
   
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
from autotranscript.__main__ import *
|
|
||||||
from autotranscript.version import get_version as _get_version
|
|
||||||
|
|
||||||
__version__ = _get_version()
|
|
||||||
@@ -1,497 +0,0 @@
|
|||||||
|
|
||||||
import whisper
|
|
||||||
from time import time, sleep
|
|
||||||
import os
|
|
||||||
import glob
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import sys
|
|
||||||
from tqdm import tqdm
|
|
||||||
|
|
||||||
from typing import Union
|
|
||||||
from pydub import AudioSegment
|
|
||||||
|
|
||||||
from pyannote.audio import Pipeline
|
|
||||||
|
|
||||||
class AudioProcessor:
|
|
||||||
def __init__(self, audio_file:str):
|
|
||||||
self.audio_file_path = audio_file
|
|
||||||
self.audio_file = AudioSegment.from_file(audio_file, format=audio_file.split('.')[-1])
|
|
||||||
|
|
||||||
self.audiofilename = audio_file.split('/')[-1][:-4]
|
|
||||||
self.coreaudiofile = audio_file.split('/')[-1][:-4]
|
|
||||||
self.audiofilefolder = os.path.dirname(audio_file)
|
|
||||||
self.audio_file_type = audio_file.split('.')[-1]
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def convert_audio(self, savefolder: str = "", savename: str = "", type: str = "wav", remove_orginal: bool = True):
|
|
||||||
"""
|
|
||||||
Convert video file or other audio files to mp3 file, ensures that the audio file is in the correct format for the
|
|
||||||
Whisper model
|
|
||||||
:param file: path to audio or video file
|
|
||||||
:param remove_orginal: remove original file
|
|
||||||
:return: mp3 file path
|
|
||||||
"""
|
|
||||||
print(f'Converting {self.audiofilename} to .{type} file')
|
|
||||||
|
|
||||||
if savefolder == "":
|
|
||||||
savefolder = self.audiofilefolder
|
|
||||||
|
|
||||||
if savename == "":
|
|
||||||
savename = self.coreaudiofile + f'.{type}'
|
|
||||||
else:
|
|
||||||
savename = savename + f'.{type}'
|
|
||||||
|
|
||||||
savepath = os.path.join(savefolder, savename)
|
|
||||||
|
|
||||||
self.audio_file.export(savepath, format=type)
|
|
||||||
|
|
||||||
print(f'Converted {self.audiofilename} to {type}')
|
|
||||||
|
|
||||||
if remove_orginal:
|
|
||||||
os.remove(self.audio_file_path)
|
|
||||||
print(f'File {self.audio_file_path} removed')
|
|
||||||
|
|
||||||
self.audio_file_path = savepath
|
|
||||||
self.audio_file = AudioSegment.from_file(savepath, format=type)
|
|
||||||
|
|
||||||
return self
|
|
||||||
|
|
||||||
def to_mp3(self, savefolder: str = "", savename: str = "", remove_orginal: bool = True):
|
|
||||||
"""
|
|
||||||
Convert audio file to mp3 file
|
|
||||||
:param file: audio file
|
|
||||||
:param remove_orginal: remove original file
|
|
||||||
:return: mp3 file path
|
|
||||||
"""
|
|
||||||
return self.convert_audio(savefolder = savefolder, savename = savename, type="mp3", remove_orginal=remove_orginal)
|
|
||||||
|
|
||||||
def to_wav(self, savefolder: str = "", savename: str = "", remove_orginal: bool = True):
|
|
||||||
"""
|
|
||||||
Convert audio file to wav file
|
|
||||||
:param file: audio file
|
|
||||||
:param remove_orginal: remove original file
|
|
||||||
:return: wav file path
|
|
||||||
"""
|
|
||||||
return self.convert_audio(savefolder = savefolder, savename = savename,type="wav", remove_orginal=remove_orginal)
|
|
||||||
|
|
||||||
def slower_mp3(self, savefolder: str = "", savename: str = "", speed: float = 0.75, type: str = "mp3"):
|
|
||||||
"""
|
|
||||||
Slow down mp3 file
|
|
||||||
:param file: mp3 file
|
|
||||||
:param speed: speed
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
if savefolder == "":
|
|
||||||
savefolder = self.audiofilefolder
|
|
||||||
else:
|
|
||||||
savefolder = savefolder
|
|
||||||
|
|
||||||
sound = self.audio_file
|
|
||||||
slow_sound = sound._spawn(sound.raw_data, overrides={
|
|
||||||
"frame_rate": int(sound.frame_rate * speed)
|
|
||||||
})
|
|
||||||
|
|
||||||
speedstr = str(speed).replace('.', '')
|
|
||||||
|
|
||||||
file_out = self.coreaudiofile + f'_{speedstr}.{type}'
|
|
||||||
|
|
||||||
save_path = os.path.join(savefolder, file_out)
|
|
||||||
|
|
||||||
slow_sound.export(save_path, format=type)
|
|
||||||
|
|
||||||
return slow_sound
|
|
||||||
|
|
||||||
class WhisperTranscription:
|
|
||||||
def __init__(self, audio_file: str , model, language: str = "German"):
|
|
||||||
|
|
||||||
self.audio_file = audio_file
|
|
||||||
self.model = model
|
|
||||||
self.language = language
|
|
||||||
|
|
||||||
def transcribe(self, language:str = "German"):
|
|
||||||
"""
|
|
||||||
Transcribe audio file
|
|
||||||
|
|
||||||
language: language of the audio file
|
|
||||||
:return: transcript as string
|
|
||||||
"""
|
|
||||||
|
|
||||||
audiofilename = self.audio_file.split('/')[-1]
|
|
||||||
#print(f'Start transcribing Audio file: {audiofilename}')
|
|
||||||
|
|
||||||
_stime = time()
|
|
||||||
result = self.model.transcribe(self.audio_file, language=self.language)
|
|
||||||
|
|
||||||
#print(f'Transcription finished in {time() - _stime} seconds')
|
|
||||||
|
|
||||||
self.transcript = result
|
|
||||||
|
|
||||||
return result["text"]
|
|
||||||
|
|
||||||
def save_transcript(self, transcript:str = "", savefolder : str = "", savename: str = ""):
|
|
||||||
"""
|
|
||||||
Save transcript to file
|
|
||||||
:param transcript: transcript as string
|
|
||||||
:param savefolder: folder to save transcript
|
|
||||||
:param savename: name of the transcript file
|
|
||||||
:return: None
|
|
||||||
"""
|
|
||||||
if savefolder == "":
|
|
||||||
savefolder = os.path.dirname(self.audio_file)
|
|
||||||
else:
|
|
||||||
savefolder = savefolder
|
|
||||||
|
|
||||||
if savename == "":
|
|
||||||
savename = self.audio_file.split('/')[-1][:-4] + '.txt'
|
|
||||||
else:
|
|
||||||
savename = savename
|
|
||||||
|
|
||||||
if transcript == "":
|
|
||||||
transcript = self.transcript["text"]
|
|
||||||
|
|
||||||
savepath = os.path.join(savefolder, savename)
|
|
||||||
|
|
||||||
with open(savepath, 'w') as f:
|
|
||||||
f.write(transcript)
|
|
||||||
|
|
||||||
print(f'Transcript saved to {savepath}')
|
|
||||||
|
|
||||||
class Diarisation(AudioProcessor):
|
|
||||||
def __init__(self, audio_file: str, model,**kwargs):
|
|
||||||
|
|
||||||
super().__init__(audio_file=audio_file)
|
|
||||||
|
|
||||||
self.model = model
|
|
||||||
|
|
||||||
|
|
||||||
def diarization(self, *args, **kwargs):
|
|
||||||
|
|
||||||
if "num_speakers" in kwargs:
|
|
||||||
num_speakers = kwargs['num_speakers']
|
|
||||||
kwargs.pop('num_speakers')
|
|
||||||
else:
|
|
||||||
num_speakers = 2
|
|
||||||
|
|
||||||
audiofilename = self.coreaudiofile
|
|
||||||
|
|
||||||
print(f'Start diarization of audio file: {self.audiofilename}')
|
|
||||||
|
|
||||||
_stime = time()
|
|
||||||
|
|
||||||
diarization = self.model(self.audio_file_path, num_speakers=num_speakers)
|
|
||||||
|
|
||||||
print(f'Diarization finished in {time() - _stime} seconds')
|
|
||||||
self.diarization = diarization
|
|
||||||
|
|
||||||
return diarization
|
|
||||||
|
|
||||||
def format_diarization_output(self, *args, **kwargs):
|
|
||||||
"""
|
|
||||||
Format diarization output to a list of tuples
|
|
||||||
:param args:
|
|
||||||
:param kwargs:
|
|
||||||
:return: dict with speaker names as keys and list of tuples as values and list of different speakers
|
|
||||||
"""
|
|
||||||
|
|
||||||
diarization_output = {"speakers": [], "segments": []}
|
|
||||||
|
|
||||||
if not hasattr(self, 'diarization'):
|
|
||||||
# ensure diarization is run before formatting
|
|
||||||
self.diarization = self.diarization()
|
|
||||||
|
|
||||||
|
|
||||||
for segment, _, speaker in self.diarization.itertracks(yield_label=True):
|
|
||||||
diarization_output["speakers"].append(speaker)
|
|
||||||
diarization_output["segments"].append(segment)
|
|
||||||
|
|
||||||
normalized_output = []
|
|
||||||
index_start_speaker = 0
|
|
||||||
index_end_speaker = 0
|
|
||||||
current_speaker = str()
|
|
||||||
|
|
||||||
for i, speaker in enumerate(diarization_output["speakers"]):
|
|
||||||
|
|
||||||
if i == 0:
|
|
||||||
current_speaker = speaker
|
|
||||||
|
|
||||||
if speaker != current_speaker:
|
|
||||||
|
|
||||||
index_end_speaker = i - 1
|
|
||||||
|
|
||||||
normalized_output.append([index_start_speaker, index_end_speaker, current_speaker])
|
|
||||||
|
|
||||||
index_start_speaker = i
|
|
||||||
current_speaker = speaker
|
|
||||||
|
|
||||||
if i == len(diarization_output["speakers"]) - 1:
|
|
||||||
|
|
||||||
index_end_speaker = i
|
|
||||||
normalized_output.append([index_start_speaker, index_end_speaker, current_speaker])
|
|
||||||
|
|
||||||
|
|
||||||
self.normalized_output = normalized_output
|
|
||||||
self.diarization_output = diarization_output
|
|
||||||
|
|
||||||
return diarization_output,normalized_output
|
|
||||||
|
|
||||||
def create_temporary_wav(self,savefolder: str = "", savename: str = "", *args, **kwargs):
|
|
||||||
"""
|
|
||||||
Create temporary wav file for diarization
|
|
||||||
:param savefolder: folder to save the temporary wav file
|
|
||||||
:param savename: name of the temporary wav file prefix
|
|
||||||
:param audiofile: audio file
|
|
||||||
:return: temporary wav file
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
if savefolder == "":
|
|
||||||
folder = '.temp'
|
|
||||||
if not os.path.exists(folder):
|
|
||||||
os.makedirs(folder)
|
|
||||||
else:
|
|
||||||
folder = savefolder
|
|
||||||
|
|
||||||
folder = os.path.realpath(folder)
|
|
||||||
|
|
||||||
if savename == "":
|
|
||||||
savename = self.coreaudiofile + '.wav'
|
|
||||||
else:
|
|
||||||
savename = savename
|
|
||||||
|
|
||||||
|
|
||||||
if not os.path.exists(folder):
|
|
||||||
os.makedirs(folder)
|
|
||||||
|
|
||||||
if not hasattr(self, 'normalized_output') or not hasattr(self, 'diarization_output'):
|
|
||||||
self.format_diarization_output()
|
|
||||||
|
|
||||||
|
|
||||||
speaker = set(self.diarization_output["speakers"])
|
|
||||||
num_speak_iter = [0 for _ in range(len(speaker))]
|
|
||||||
|
|
||||||
for count, outp in enumerate(self.normalized_output):
|
|
||||||
start = self.diarization_output["segments"][outp[0]].start
|
|
||||||
end = self.diarization_output["segments"][outp[1]].end
|
|
||||||
|
|
||||||
print("start: ", start)
|
|
||||||
print("end: ", end)
|
|
||||||
|
|
||||||
start_milliseconds = start * 1000
|
|
||||||
end_milliseconds = end * 1000
|
|
||||||
|
|
||||||
print("start_milliseconds: ", start_milliseconds)
|
|
||||||
print("end_milliseconds: ", end_milliseconds)
|
|
||||||
|
|
||||||
print("cut audio")
|
|
||||||
|
|
||||||
cut_audio = self.audio_file[start_milliseconds:end_milliseconds]
|
|
||||||
|
|
||||||
print("save audio")
|
|
||||||
print(f".temp/{count}_speaker_" + str(outp[2]) + ".wav")
|
|
||||||
cut_audio.export(f".temp/{count}_speaker_" + str(outp[2]) + ".wav", format="wav")
|
|
||||||
|
|
||||||
return os.path.realpath(folder)
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return f"Diarization(audiofile={self.audiofile}, model={self.model}, language={self.language})"
|
|
||||||
def __str__(self):
|
|
||||||
return f"Diarization(audiofile={self.audiofile}, model={self.model}, language={self.language})"
|
|
||||||
|
|
||||||
|
|
||||||
class AutoTranscribe:
|
|
||||||
def __init__(self, audiofile: Union[str, bool, list] = None,
|
|
||||||
model: str = "medium",
|
|
||||||
language: str = "German",
|
|
||||||
diarisation: bool = False,
|
|
||||||
audioinput: str = "audiofiles",
|
|
||||||
transcriptionout: str = "transcriptions",
|
|
||||||
*args, **kwargs):
|
|
||||||
"""
|
|
||||||
AutoTranscribe
|
|
||||||
:param audiofile: audio file or list of audio files to transcribe
|
|
||||||
:param model: model name (default: medium)
|
|
||||||
:param language: language (default: German)
|
|
||||||
:param diarisation: diarisation (default: False)
|
|
||||||
"""
|
|
||||||
if audiofile is None:
|
|
||||||
audiofile = os.listdir(audioinput) # get all audio files in audioinput folder
|
|
||||||
audiofile = [os.path.realpath(os.path.join(audioinput, file)) for file in audiofile]# add path to audio files
|
|
||||||
|
|
||||||
self.audiofile = audiofile
|
|
||||||
self.language = language
|
|
||||||
self.diarisation = diarisation
|
|
||||||
if diarisation:
|
|
||||||
print("Diarisation is enabled")
|
|
||||||
print("Load Diarisation model")
|
|
||||||
self.diarisation_model = Pipeline.from_pretrained("pyannote/speaker-diarization",
|
|
||||||
use_auth_token = self._get_token())
|
|
||||||
print("Load Diarisation model done")
|
|
||||||
|
|
||||||
print(f"Load Whisper model {model}")
|
|
||||||
self.model = whisper.load_model(model)
|
|
||||||
print(f"Load Whisper model {model} done")
|
|
||||||
|
|
||||||
self.currentpath, \
|
|
||||||
self.audiopath, \
|
|
||||||
self.transcriptionpath, \
|
|
||||||
self.audiofiles = self.create_folder_structure(audioinput, transcriptionout) # create folder structure
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def transcribe(self, *args, **kwargs):
|
|
||||||
|
|
||||||
if isinstance(self.audiofile, str):
|
|
||||||
for i in range(len(self.audiofiles)):
|
|
||||||
if self.audiofile in self.audiofiles[i]:
|
|
||||||
self.audiofile = [self.audiofiles[i]]
|
|
||||||
break
|
|
||||||
|
|
||||||
audiolist = self.audiofile
|
|
||||||
|
|
||||||
elif isinstance(self.audiofile, list):
|
|
||||||
audiolist = self.audiofile
|
|
||||||
else:
|
|
||||||
audiolist = self.audiofiles
|
|
||||||
|
|
||||||
if not set(audiolist).issubset(set(self.audiofiles)):
|
|
||||||
raise ValueError(f"Audio file {self.audiofile} not found in {self.audiopath}")
|
|
||||||
|
|
||||||
|
|
||||||
for audiofile in audiolist:
|
|
||||||
_start = time()
|
|
||||||
if not "/" in audiofile:
|
|
||||||
audiofile = os.path.join(self.audiopath, audiofile)
|
|
||||||
|
|
||||||
if not self.check_if_already_transcribed (audiofile):
|
|
||||||
|
|
||||||
audio = AudioProcessor(audiofile)
|
|
||||||
|
|
||||||
if not audiofile.endswith('wav'):
|
|
||||||
audio = audio.to_wav()
|
|
||||||
self.audiofile = audio.audio_file_path
|
|
||||||
audiofile = audio.audio_file_path
|
|
||||||
|
|
||||||
if "speed" in kwargs:
|
|
||||||
speed = kwargs['speed']
|
|
||||||
kwargs.pop('speed')
|
|
||||||
|
|
||||||
print('Creating slower version of the audio file with speed {}'.format(speed))
|
|
||||||
slower_audio = os.path.join(self.transcriptionpath, 'slower_version')
|
|
||||||
if not os.path.exists(slower_audio):
|
|
||||||
os.makedirs(slower_audio)
|
|
||||||
audio.slower_mp3(savefolder=slower_audio,speed=speed)
|
|
||||||
|
|
||||||
if not self.diarisation:
|
|
||||||
WhisperTranscription(audiofile, self.model, self.language
|
|
||||||
).save_transcript(savefolder = self.transcriptionpath)
|
|
||||||
|
|
||||||
else:
|
|
||||||
print("Start diarisation")
|
|
||||||
dia = Diarisation(audiofile, self.diarisation_model)
|
|
||||||
|
|
||||||
if 'num_speakers' in kwargs:
|
|
||||||
num_speakers = kwargs['num_speakers']
|
|
||||||
kwargs.pop('num_speakers')
|
|
||||||
dia.diarization(num_speakers=num_speakers)
|
|
||||||
else:
|
|
||||||
dia.diarization()
|
|
||||||
|
|
||||||
temppath = dia.create_temporary_wav()
|
|
||||||
temppath_dict, _ = dia.format_diarization_output()
|
|
||||||
speakers = list(set(temppath_dict["speakers"]))
|
|
||||||
|
|
||||||
|
|
||||||
fstring = "\\begin{drama}"
|
|
||||||
|
|
||||||
for speaker in speakers:
|
|
||||||
speaker = speaker.replace("SPEAKER_", "")
|
|
||||||
fstring += "\n\t\Character{S"+ str(speaker) + "}{S" + str(speaker) + "}"
|
|
||||||
|
|
||||||
|
|
||||||
files = glob.glob(temppath + "/*.wav")
|
|
||||||
|
|
||||||
# Sort files according to the digits included in the filename
|
|
||||||
files = sorted(files, key=lambda x: float(re.findall("(\d+)", x)[0]))
|
|
||||||
|
|
||||||
for file in tqdm(files):
|
|
||||||
|
|
||||||
Whisper = WhisperTranscription(file, self.model, self.language).transcribe()
|
|
||||||
|
|
||||||
for s in speakers:
|
|
||||||
if s in file:
|
|
||||||
s = s.replace("SPEAKER_", "")
|
|
||||||
fstring += f"\n\S{s}speaks: \n {Whisper}"
|
|
||||||
|
|
||||||
fstring += "\n\end{drama}"
|
|
||||||
|
|
||||||
print(fstring)
|
|
||||||
|
|
||||||
with open(os.path.join(self.transcriptionpath,
|
|
||||||
os.path.basename(audiofile).split('.')[0] + '.tex'), 'w') as f:
|
|
||||||
f.write(fstring)
|
|
||||||
|
|
||||||
print("Remove temporary files")
|
|
||||||
shutil.rmtree(temppath)
|
|
||||||
|
|
||||||
print(f"Transcription of {audiofile} done in total of {time() - _start} seconds")
|
|
||||||
|
|
||||||
def create_folder_structure(self, audiopath: str, transcriptionout: str):
|
|
||||||
"""
|
|
||||||
Create folder structure for audio and transcription files
|
|
||||||
|
|
||||||
:return: currentpath, audiopath, transcriptionpath, audiofiles
|
|
||||||
"""
|
|
||||||
currentpath = os.path.dirname(sys.argv[0]) # get executable path
|
|
||||||
|
|
||||||
if not os.path.exists(os.path.join(currentpath, audiopath)):
|
|
||||||
print('Creating audiofiles folder')
|
|
||||||
os.makedirs(os.path.join(currentpath, audiopath))
|
|
||||||
if not os.path.exists(os.path.join(currentpath, transcriptionout)):
|
|
||||||
print('Creating transcription folder')
|
|
||||||
os.makedirs(os.path.join(currentpath, transcriptionout))
|
|
||||||
|
|
||||||
audiopath = os.path.join(currentpath, audiopath) # path to audio files
|
|
||||||
transcriptionpath = os.path.join(currentpath, transcriptionout) # path to transcription files
|
|
||||||
|
|
||||||
|
|
||||||
_audiofiles = os.listdir(audiopath) # list of audio files
|
|
||||||
audiofiles = []
|
|
||||||
for i in _audiofiles:
|
|
||||||
audiofiles.append(os.path.join(audiopath, i))
|
|
||||||
|
|
||||||
return currentpath, audiopath, transcriptionpath, audiofiles
|
|
||||||
|
|
||||||
def check_if_already_transcribed (self, filename: str):
|
|
||||||
"""
|
|
||||||
Check if all audio files are already transcribed
|
|
||||||
:param filename: audio file name
|
|
||||||
:return: bool
|
|
||||||
"""
|
|
||||||
purefilename = filename.split('/')[-1][:-4]
|
|
||||||
_files = os.listdir(self.transcriptionpath)
|
|
||||||
for i,f in enumerate(_files):
|
|
||||||
_files[i] = f[:-4]
|
|
||||||
|
|
||||||
if purefilename in _files:
|
|
||||||
print(f'File {purefilename[:-4]} already transcribed')
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
@classmethod
|
|
||||||
def _get_token(self):
|
|
||||||
# check ig .pyannotetoken.txt exists
|
|
||||||
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.pyannotetoken')
|
|
||||||
if os.path.exists(path):
|
|
||||||
with open(path, 'r') as f:
|
|
||||||
token = f.read()
|
|
||||||
else:
|
|
||||||
raise ValueError('No token found. Please create a token at https://huggingface.co/settings/token'
|
|
||||||
' and save it in a file called .pyannotetoken.txt')
|
|
||||||
return token
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return f"AutoTranscribe(audiofile={self.audiofile}, model={self.model}, language={self.language}, diarisation={self.diarisation})"
|
|
||||||
def __call__(self, *args, **kwargs):
|
|
||||||
return self.transcribe(*args, **kwargs)
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
name: whisper
|
|
||||||
channels:
|
channels:
|
||||||
- pytorch
|
- pytorch
|
||||||
- defaults
|
- defaults
|
||||||
@@ -11,7 +10,7 @@ dependencies:
|
|||||||
- ca-certificates=2023.05.30=h06a4308_0
|
- ca-certificates=2023.05.30=h06a4308_0
|
||||||
- certifi=2023.5.7=py39h06a4308_0
|
- certifi=2023.5.7=py39h06a4308_0
|
||||||
- cffi=1.15.1=py39h5eee18b_3
|
- cffi=1.15.1=py39h5eee18b_3
|
||||||
- cryptography=39.0.1=py39h9ce1e76_0
|
- cryptography=39.0.1=py39h9ce1e76_2
|
||||||
- cudatoolkit=11.3.1=h2bc3f7f_2
|
- cudatoolkit=11.3.1=h2bc3f7f_2
|
||||||
- ffmpeg=4.2.2=h20bf706_0
|
- ffmpeg=4.2.2=h20bf706_0
|
||||||
- flit-core=3.8.0=py39h06a4308_0
|
- flit-core=3.8.0=py39h06a4308_0
|
||||||
@@ -51,36 +50,40 @@ dependencies:
|
|||||||
- numpy=1.23.5=py39h14f4228_0
|
- numpy=1.23.5=py39h14f4228_0
|
||||||
- numpy-base=1.23.5=py39h31eccc5_0
|
- numpy-base=1.23.5=py39h31eccc5_0
|
||||||
- openh264=2.1.1=h4ff587b_0
|
- openh264=2.1.1=h4ff587b_0
|
||||||
- openssl=1.1.1t=h7f8727e_0
|
- openssl=3.0.9=h7f8727e_0
|
||||||
- pillow=9.4.0=py39h6a678d5_0
|
- pillow=9.4.0=py39h6a678d5_0
|
||||||
- pip=23.0.1=py39h06a4308_0
|
- pip=23.0.1=py39h06a4308_0
|
||||||
- pycparser=2.21=pyhd3eb1b0_0
|
- pycparser=2.21=pyhd3eb1b0_0
|
||||||
- pyopenssl=23.0.0=py39h06a4308_0
|
- pyopenssl=23.0.0=py39h06a4308_0
|
||||||
- pysocks=1.7.1=py39h06a4308_0
|
- pysocks=1.7.1=py39h06a4308_0
|
||||||
- python=3.9.16=h7a1cb2a_2
|
- python=3.9.16=h955ad1f_3
|
||||||
- pytorch=1.11.0=py3.9_cuda11.3_cudnn8.2.0_0
|
- pytorch=1.11.0=py3.9_cuda11.3_cudnn8.2.0_0
|
||||||
- pytorch-mutex=1.0=cuda
|
- pytorch-mutex=1.0=cuda
|
||||||
- readline=8.2=h5eee18b_0
|
- readline=8.2=h5eee18b_0
|
||||||
- requests=2.28.1=py39h06a4308_1
|
- requests=2.28.1=py39h06a4308_1
|
||||||
- setuptools=65.6.3=py39h06a4308_0
|
- setuptools=65.6.3=py39h06a4308_0
|
||||||
- six=1.16.0=pyhd3eb1b0_1
|
- six=1.16.0=pyhd3eb1b0_1
|
||||||
- sqlite=3.41.1=h5eee18b_0
|
- sqlite=3.41.2=h5eee18b_0
|
||||||
- tk=8.6.12=h1ccaba5_0
|
- tk=8.6.12=h1ccaba5_0
|
||||||
- torchaudio=0.11.0=py39_cu113
|
- torchaudio=0.11.0=py39_cu113
|
||||||
- torchvision=0.12.0=py39_cu113
|
- torchvision=0.12.0=py39_cu113
|
||||||
- typing_extensions=4.4.0=py39h06a4308_0
|
|
||||||
- tzdata=2023c=h04d1e81_0
|
- tzdata=2023c=h04d1e81_0
|
||||||
- wheel=0.38.4=py39h06a4308_0
|
- wheel=0.38.4=py39h06a4308_0
|
||||||
- x264=1!157.20191217=h7b6447c_0
|
- x264=1!157.20191217=h7b6447c_0
|
||||||
- xz=5.2.10=h5eee18b_1
|
- xz=5.4.2=h5eee18b_0
|
||||||
- zlib=1.2.13=h5eee18b_0
|
- zlib=1.2.13=h5eee18b_0
|
||||||
- zstd=1.5.4=hc292b87_0
|
- zstd=1.5.4=hc292b87_0
|
||||||
- pip:
|
- pip:
|
||||||
- absl-py==1.3.0
|
- absl-py==1.3.0
|
||||||
|
- aiofiles==23.1.0
|
||||||
- aiohttp==3.8.3
|
- aiohttp==3.8.3
|
||||||
- aiosignal==1.3.1
|
- aiosignal==1.3.1
|
||||||
- alembic==1.9.1
|
- alembic==1.9.1
|
||||||
|
- altair==5.0.1
|
||||||
|
- annotated-types==0.5.0
|
||||||
|
- ansi2html==1.8.0
|
||||||
- antlr4-python3-runtime==4.9.3
|
- antlr4-python3-runtime==4.9.3
|
||||||
|
- anyio==3.7.1
|
||||||
- appdirs==1.4.4
|
- appdirs==1.4.4
|
||||||
- asteroid-filterbanks==0.4.0
|
- asteroid-filterbanks==0.4.0
|
||||||
- async-timeout==4.0.2
|
- async-timeout==4.0.2
|
||||||
@@ -100,48 +103,76 @@ dependencies:
|
|||||||
- commonmark==0.9.1
|
- commonmark==0.9.1
|
||||||
- contourpy==1.0.6
|
- contourpy==1.0.6
|
||||||
- cycler==0.11.0
|
- cycler==0.11.0
|
||||||
|
- dash==2.12.1
|
||||||
|
- dash-core-components==2.0.0
|
||||||
|
- dash-html-components==2.0.0
|
||||||
|
- dash-table==5.0.0
|
||||||
- decorator==4.4.2
|
- decorator==4.4.2
|
||||||
- docopt==0.6.2
|
- docopt==0.6.2
|
||||||
- einops==0.3.2
|
- einops==0.3.2
|
||||||
|
- exceptiongroup==1.1.1
|
||||||
|
- fastapi==0.100.0
|
||||||
- ffmpeg-python==0.2.0
|
- ffmpeg-python==0.2.0
|
||||||
|
- ffmpy==0.3.0
|
||||||
- filelock==3.8.0
|
- filelock==3.8.0
|
||||||
|
- flask==2.2.5
|
||||||
- fonttools==4.38.0
|
- fonttools==4.38.0
|
||||||
- frozenlist==1.3.3
|
- frozenlist==1.3.3
|
||||||
- fsspec==2022.11.0
|
- fsspec==2022.11.0
|
||||||
- future==0.18.2
|
- future==0.18.2
|
||||||
- google-auth==2.15.0
|
- google-auth==2.15.0
|
||||||
- google-auth-oauthlib==0.4.6
|
- google-auth-oauthlib==0.4.6
|
||||||
|
- gradio==3.36.1
|
||||||
|
- gradio-client==0.2.7
|
||||||
- greenlet==2.0.1
|
- greenlet==2.0.1
|
||||||
- grpcio==1.51.1
|
- grpcio==1.51.1
|
||||||
|
- h11==0.14.0
|
||||||
- hmmlearn==0.2.8
|
- hmmlearn==0.2.8
|
||||||
- huggingface-hub==0.11.0
|
- httpcore==0.17.3
|
||||||
|
- httpx==0.24.1
|
||||||
|
- huggingface-hub==0.16.4
|
||||||
|
- humanize==4.7.0
|
||||||
- hyperpyyaml==1.1.0
|
- hyperpyyaml==1.1.0
|
||||||
- imageio==2.23.0
|
- imageio==2.23.0
|
||||||
- imageio-ffmpeg==0.4.7
|
- imageio-ffmpeg==0.4.7
|
||||||
- importlib-metadata==4.13.0
|
- importlib-metadata==4.13.0
|
||||||
|
- importlib-resources==5.12.0
|
||||||
|
- iniconfig==2.0.0
|
||||||
|
- itsdangerous==2.1.2
|
||||||
|
- jinja2==3.1.2
|
||||||
- joblib==1.2.0
|
- joblib==1.2.0
|
||||||
|
- jsonschema==4.18.0
|
||||||
|
- jsonschema-specifications==2023.6.1
|
||||||
- julius==0.2.7
|
- julius==0.2.7
|
||||||
- kiwisolver==1.4.4
|
- kiwisolver==1.4.4
|
||||||
- librosa==0.9.2
|
- librosa==0.9.2
|
||||||
|
- linkify-it-py==2.0.2
|
||||||
- lit==16.0.5.post0
|
- lit==16.0.5.post0
|
||||||
- llvmlite==0.39.1
|
- llvmlite==0.39.1
|
||||||
- mako==1.2.4
|
- mako==1.2.4
|
||||||
- markdown==3.4.1
|
- markdown==3.4.1
|
||||||
|
- markdown-it-py==2.2.0
|
||||||
- markupsafe==2.1.1
|
- markupsafe==2.1.1
|
||||||
- matplotlib==3.6.2
|
- matplotlib==3.7.1
|
||||||
|
- mdit-py-plugins==0.3.3
|
||||||
|
- mdurl==0.1.2
|
||||||
- more-itertools==9.0.0
|
- more-itertools==9.0.0
|
||||||
- moviepy==1.0.3
|
- moviepy==1.0.3
|
||||||
- mpmath==1.2.1
|
- mpmath==1.2.1
|
||||||
- multidict==6.0.4
|
- multidict==6.0.4
|
||||||
|
- nest-asyncio==1.5.7
|
||||||
- networkx==2.8.8
|
- networkx==2.8.8
|
||||||
- numba==0.56.4
|
- numba==0.56.4
|
||||||
- oauthlib==3.2.2
|
- oauthlib==3.2.2
|
||||||
- omegaconf==2.3.0
|
- omegaconf==2.3.0
|
||||||
- openai-whisper==20230314
|
- openai-whisper==20230314
|
||||||
- optuna==3.0.5
|
- optuna==3.0.5
|
||||||
|
- orjson==3.9.2
|
||||||
- packaging==21.3
|
- packaging==21.3
|
||||||
- pandas==1.5.2
|
- pandas==1.5.2
|
||||||
- pbr==5.11.0
|
- pbr==5.11.0
|
||||||
|
- plotly==5.15.0
|
||||||
|
- pluggy==1.0.0
|
||||||
- pooch==1.6.0
|
- pooch==1.6.0
|
||||||
- prettytable==3.5.0
|
- prettytable==3.5.0
|
||||||
- primepy==1.3
|
- primepy==1.3
|
||||||
@@ -154,23 +185,32 @@ dependencies:
|
|||||||
- pyannote-pipeline==2.3
|
- pyannote-pipeline==2.3
|
||||||
- pyasn1==0.4.8
|
- pyasn1==0.4.8
|
||||||
- pyasn1-modules==0.2.8
|
- pyasn1-modules==0.2.8
|
||||||
|
- pydantic==2.0.2
|
||||||
|
- pydantic-core==2.1.2
|
||||||
- pydeprecate==0.3.2
|
- pydeprecate==0.3.2
|
||||||
- pydub==0.25.1
|
- pydub==0.25.1
|
||||||
- pygments==2.13.0
|
- pygments==2.13.0
|
||||||
- pyparsing==3.0.9
|
- pyparsing==3.0.9
|
||||||
- pyperclip==1.8.2
|
- pyperclip==1.8.2
|
||||||
|
- pytest==7.3.1
|
||||||
- python-dateutil==2.8.2
|
- python-dateutil==2.8.2
|
||||||
|
- python-multipart==0.0.6
|
||||||
- pytorch-lightning==1.6.5
|
- pytorch-lightning==1.6.5
|
||||||
- pytorch-metric-learning==1.6.3
|
- pytorch-metric-learning==1.6.3
|
||||||
- pytz==2022.7
|
- pytz==2022.7
|
||||||
- pyyaml==6.0
|
- pyyaml==6.0
|
||||||
|
- qtfaststart==1.8
|
||||||
|
- referencing==0.29.1
|
||||||
- regex==2022.10.31
|
- regex==2022.10.31
|
||||||
- requests-oauthlib==1.3.1
|
- requests-oauthlib==1.3.1
|
||||||
- resampy==0.4.2
|
- resampy==0.4.2
|
||||||
|
- retrying==1.3.4
|
||||||
- rich==12.6.0
|
- rich==12.6.0
|
||||||
|
- rpds-py==0.8.10
|
||||||
- rsa==4.9
|
- rsa==4.9
|
||||||
- ruamel-yaml==0.17.21
|
- ruamel-yaml==0.17.21
|
||||||
- ruamel-yaml-clib==0.2.7
|
- ruamel-yaml-clib==0.2.7
|
||||||
|
- ruff==0.0.272
|
||||||
- scikit-learn==1.2.0
|
- scikit-learn==1.2.0
|
||||||
- scipy==1.8.1
|
- scipy==1.8.1
|
||||||
- semantic-version==2.10.0
|
- semantic-version==2.10.0
|
||||||
@@ -180,19 +220,24 @@ dependencies:
|
|||||||
- shellingham==1.5.0
|
- shellingham==1.5.0
|
||||||
- simplejson==3.18.0
|
- simplejson==3.18.0
|
||||||
- singledispatchmethod==1.0
|
- singledispatchmethod==1.0
|
||||||
|
- sniffio==1.3.0
|
||||||
- sortedcontainers==2.4.0
|
- sortedcontainers==2.4.0
|
||||||
- soundfile==0.10.3.post1
|
- soundfile==0.10.3.post1
|
||||||
- speechbrain==0.5.13
|
- speechbrain==0.5.14
|
||||||
- sqlalchemy==1.4.45
|
- sqlalchemy==1.4.45
|
||||||
|
- starlette==0.27.0
|
||||||
- stevedore==4.1.1
|
- stevedore==4.1.1
|
||||||
- sympy==1.11.1
|
- sympy==1.11.1
|
||||||
- tabulate==0.9.0
|
- tabulate==0.9.0
|
||||||
|
- tenacity==8.2.2
|
||||||
- tensorboard==2.11.0
|
- tensorboard==2.11.0
|
||||||
- tensorboard-data-server==0.6.1
|
- tensorboard-data-server==0.6.1
|
||||||
- tensorboard-plugin-wit==1.8.1
|
- tensorboard-plugin-wit==1.8.1
|
||||||
- threadpoolctl==3.1.0
|
- threadpoolctl==3.1.0
|
||||||
- tiktoken==0.3.1
|
- tiktoken==0.3.1
|
||||||
- tokenizers==0.13.2
|
- tokenizers==0.13.2
|
||||||
|
- tomli==2.0.1
|
||||||
|
- toolz==0.12.0
|
||||||
- torch-audiomentations==0.11.0
|
- torch-audiomentations==0.11.0
|
||||||
- torch-pitch-shift==1.2.2
|
- torch-pitch-shift==1.2.2
|
||||||
- torchmetrics==0.11.0
|
- torchmetrics==0.11.0
|
||||||
@@ -200,8 +245,12 @@ dependencies:
|
|||||||
- transformers==4.24.0
|
- transformers==4.24.0
|
||||||
- triton==2.0.0
|
- triton==2.0.0
|
||||||
- typer==0.7.0
|
- typer==0.7.0
|
||||||
|
- typing-extensions==4.7.1
|
||||||
|
- uc-micro-py==1.0.2
|
||||||
- urllib3==1.26.12
|
- urllib3==1.26.12
|
||||||
|
- uvicorn==0.22.0
|
||||||
- wcwidth==0.2.5
|
- wcwidth==0.2.5
|
||||||
|
- websockets==11.0.3
|
||||||
- werkzeug==2.2.2
|
- werkzeug==2.2.2
|
||||||
- yarl==1.8.2
|
- yarl==1.8.2
|
||||||
- zipp==3.11.0
|
- zipp==3.11.0
|
||||||
|
|||||||
@@ -1,152 +1,25 @@
|
|||||||
absl-py==1.3.0
|
|
||||||
aiohttp==3.8.3
|
|
||||||
aiosignal==1.3.1
|
|
||||||
alembic==1.9.1
|
|
||||||
antlr4-python3-runtime==4.9.3
|
|
||||||
appdirs==1.4.4
|
|
||||||
asteroid-filterbanks==0.4.0
|
|
||||||
async-timeout==4.0.2
|
|
||||||
attrs==22.2.0
|
|
||||||
audioread==3.0.0
|
|
||||||
autopage==0.5.1
|
|
||||||
backports.cached-property==1.0.2
|
|
||||||
brotlipy==0.7.0
|
|
||||||
cachetools==5.2.0
|
|
||||||
certifi==2023.5.7
|
|
||||||
cffi==1.15.1
|
|
||||||
charset-normalizer==2.1.1
|
|
||||||
click==8.1.3
|
|
||||||
cliff==4.1.0
|
|
||||||
cmaes==0.9.0
|
|
||||||
cmake==3.26.4
|
|
||||||
cmd2==2.4.2
|
|
||||||
colorama==0.4.6
|
|
||||||
colorlog==6.7.0
|
|
||||||
commonmark==0.9.1
|
|
||||||
contourpy==1.0.6
|
|
||||||
cryptography==39.0.1
|
|
||||||
cycler==0.11.0
|
|
||||||
decorator==4.4.2
|
|
||||||
docopt==0.6.2
|
|
||||||
einops==0.3.2
|
|
||||||
ffmpeg-python==0.2.0
|
|
||||||
filelock==3.8.0
|
|
||||||
flit_core==3.8.0
|
|
||||||
fonttools==4.38.0
|
|
||||||
frozenlist==1.3.3
|
|
||||||
fsspec==2022.11.0
|
|
||||||
future==0.18.2
|
|
||||||
google-auth==2.15.0
|
|
||||||
google-auth-oauthlib==0.4.6
|
|
||||||
greenlet==2.0.1
|
|
||||||
grpcio==1.51.1
|
|
||||||
hmmlearn==0.2.8
|
|
||||||
huggingface-hub==0.11.0
|
|
||||||
HyperPyYAML==1.1.0
|
|
||||||
idna==3.4
|
|
||||||
imageio==2.23.0
|
|
||||||
imageio-ffmpeg==0.4.7
|
|
||||||
importlib-metadata==4.13.0
|
|
||||||
joblib==1.2.0
|
|
||||||
julius==0.2.7
|
|
||||||
kiwisolver==1.4.4
|
|
||||||
librosa==0.9.2
|
|
||||||
lit==16.0.5.post0
|
|
||||||
llvmlite==0.39.1
|
|
||||||
Mako==1.2.4
|
|
||||||
Markdown==3.4.1
|
|
||||||
MarkupSafe==2.1.1
|
|
||||||
matplotlib==3.6.2
|
|
||||||
mkl-fft==1.3.1
|
|
||||||
mkl-random==1.2.2
|
|
||||||
mkl-service==2.4.0
|
|
||||||
more-itertools==9.0.0
|
|
||||||
moviepy==1.0.3
|
|
||||||
mpmath==1.2.1
|
|
||||||
multidict==6.0.4
|
|
||||||
networkx==2.8.8
|
|
||||||
numba==0.56.4
|
|
||||||
numpy==1.23.5
|
|
||||||
oauthlib==3.2.2
|
|
||||||
omegaconf==2.3.0
|
|
||||||
openai-whisper==20230314
|
openai-whisper==20230314
|
||||||
optuna==3.0.5
|
|
||||||
packaging==21.3
|
pyannote.audio~=2.1.1
|
||||||
pandas==1.5.2
|
pyannote.core~=4.5
|
||||||
pbr==5.11.0
|
pyannote.database~=4.1.3
|
||||||
Pillow==9.4.0
|
pyannote.metrics~=3.2.1
|
||||||
pip==23.0.1
|
pyannote.pipeline~=2.3
|
||||||
pooch==1.6.0
|
|
||||||
prettytable==3.5.0
|
setuptools~=65.6.3
|
||||||
primePy==1.3
|
setuptools-rust~=1.5.2
|
||||||
proglog==0.1.10
|
|
||||||
protobuf==3.20.1
|
tqdm>=4.65.0
|
||||||
pyannote.audio==2.1.1
|
|
||||||
pyannote.core==4.5
|
gradio~=3.36.1
|
||||||
pyannote.database==4.1.3
|
gradio-client~=0.2.7
|
||||||
pyannote.metrics==3.2.1
|
|
||||||
pyannote.pipeline==2.3
|
# add pytorch to override the one installed by pyannote.audio
|
||||||
pyasn1==0.4.8
|
|
||||||
pyasn1-modules==0.2.8
|
torch~=1.11.0
|
||||||
pycparser==2.21
|
torchvision~=0.12.0
|
||||||
pyDeprecate==0.3.2
|
torchaudio~=0.11.0
|
||||||
pydub==0.25.1
|
#optional:
|
||||||
Pygments==2.13.0
|
#sphinx~=5.0.2
|
||||||
pyOpenSSL==23.0.0
|
|
||||||
pyparsing==3.0.9
|
|
||||||
pyperclip==1.8.2
|
|
||||||
PySocks==1.7.1
|
|
||||||
python-dateutil==2.8.2
|
|
||||||
pytorch-lightning==1.6.5
|
|
||||||
pytorch-metric-learning==1.6.3
|
|
||||||
pytz==2022.7
|
|
||||||
PyYAML==6.0
|
|
||||||
regex==2022.10.31
|
|
||||||
requests==2.28.1
|
|
||||||
requests-oauthlib==1.3.1
|
|
||||||
resampy==0.4.2
|
|
||||||
rich==12.6.0
|
|
||||||
rsa==4.9
|
|
||||||
ruamel.yaml==0.17.21
|
|
||||||
ruamel.yaml.clib==0.2.7
|
|
||||||
scikit-learn==1.2.0
|
|
||||||
scipy==1.8.1
|
|
||||||
semantic-version==2.10.0
|
|
||||||
semver==2.13.0
|
|
||||||
sentencepiece==0.1.97
|
|
||||||
setuptools==65.6.3
|
|
||||||
setuptools-rust==1.5.2
|
|
||||||
shellingham==1.5.0
|
|
||||||
simplejson==3.18.0
|
|
||||||
singledispatchmethod==1.0
|
|
||||||
six==1.16.0
|
|
||||||
sortedcontainers==2.4.0
|
|
||||||
SoundFile==0.10.3.post1
|
|
||||||
speechbrain==0.5.13
|
|
||||||
SQLAlchemy==1.4.45
|
|
||||||
stevedore==4.1.1
|
|
||||||
sympy==1.11.1
|
|
||||||
tabulate==0.9.0
|
|
||||||
tensorboard==2.11.0
|
|
||||||
tensorboard-data-server==0.6.1
|
|
||||||
tensorboard-plugin-wit==1.8.1
|
|
||||||
threadpoolctl==3.1.0
|
|
||||||
tiktoken==0.3.1
|
|
||||||
tokenizers==0.13.2
|
|
||||||
torch==1.11.0
|
|
||||||
torch-audiomentations==0.11.0
|
|
||||||
torch-pitch-shift==1.2.2
|
|
||||||
torchaudio==0.11.0
|
|
||||||
torchmetrics==0.11.0
|
|
||||||
torchvision==0.12.0
|
|
||||||
tqdm==4.65.0
|
|
||||||
transformers==4.24.0
|
|
||||||
triton==2.0.0
|
|
||||||
typer==0.7.0
|
|
||||||
typing_extensions==4.4.0
|
|
||||||
urllib3==1.26.15
|
|
||||||
wcwidth==0.2.5
|
|
||||||
Werkzeug==2.2.2
|
|
||||||
wheel==0.38.4
|
|
||||||
yarl==1.8.2
|
|
||||||
zipp==3.11.0
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from .autotranscript import *
|
||||||
|
from .transcriber import *
|
||||||
|
from .audio import *
|
||||||
|
from .transcript_exporter import *
|
||||||
|
from .diarisation import *
|
||||||
|
|
||||||
|
from .version import get_version as _get_version
|
||||||
|
from .misc import *
|
||||||
|
|
||||||
|
from .app.gradio_app import *
|
||||||
|
from .app.qtfaststart import *
|
||||||
|
|
||||||
|
from .cli import *
|
||||||
|
|
||||||
|
__version__ = _get_version()
|
||||||
|
After Width: | Height: | Size: 38 KiB |
@@ -0,0 +1,2 @@
|
|||||||
|
from .qtfaststart import *
|
||||||
|
from .gradio_app import *
|
||||||
@@ -0,0 +1,438 @@
|
|||||||
|
"""
|
||||||
|
Gradio Audio Transcription App.
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
This module provides an interface to transcribe audio files using the
|
||||||
|
Scraibe model. Users can either upload an audio file or record their speech
|
||||||
|
live for transcription. The application supports multiple languages and provides
|
||||||
|
options to specify the number of speakers and the language of the audio.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
LANGUAGES (list): A list of supported languages for transcription.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
Run this script to start the Gradio web interface for audio transcription.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
"""
|
||||||
|
Gradio Audio Transcription App.
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
This module provides an interface to transcribe audio files using the
|
||||||
|
Scraibe model. Users can either upload an audio file or record their speech
|
||||||
|
live for transcription. The application supports multiple languages and provides
|
||||||
|
options to specify the number of speakers and the language of the audio.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
LANGUAGES (list): A list of supported languages for transcription.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
Run this script to start the Gradio web interface for audio transcription.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from tkinter import CURRENT
|
||||||
|
|
||||||
|
import gradio as gr
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
from scraibe import Scraibe, Transcript
|
||||||
|
|
||||||
|
theme = gr.themes.Soft(
|
||||||
|
primary_hue="green",
|
||||||
|
secondary_hue='orange',
|
||||||
|
neutral_hue="gray",
|
||||||
|
)
|
||||||
|
|
||||||
|
LANGUAGES = [
|
||||||
|
"Afrikaans", "Arabic", "Armenian", "Azerbaijani", "Belarusian",
|
||||||
|
"Bosnian", "Bulgarian", "Catalan", "Chinese", "Croatian",
|
||||||
|
"Czech", "Danish", "Dutch", "English", "Estonian",
|
||||||
|
"Finnish", "French", "Galician", "German", "Greek",
|
||||||
|
"Hebrew", "Hindi", "Hungarian", "Icelandic", "Indonesian",
|
||||||
|
"Italian", "Japanese", "Kannada", "Kazakh", "Korean",
|
||||||
|
"Latvian", "Lithuanian", "Macedonian", "Malay", "Marathi",
|
||||||
|
"Maori", "Nepali", "Norwegian", "Persian", "Polish",
|
||||||
|
"Portuguese", "Romanian", "Russian", "Serbian", "Slovak",
|
||||||
|
"Slovenian", "Spanish", "Swahili", "Swedish", "Tagalog",
|
||||||
|
"Tamil", "Thai", "Turkish", "Ukrainian", "Urdu",
|
||||||
|
"Vietnamese", "Welsh"
|
||||||
|
]
|
||||||
|
|
||||||
|
CURRENT_PATH = os.path.dirname(os.path.realpath(__file__))
|
||||||
|
|
||||||
|
class GradioTranscriptionInterface:
|
||||||
|
"""
|
||||||
|
Interface handling the interaction between Gradio UI and the Audio Transcription system.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, model: Scraibe):
|
||||||
|
"""
|
||||||
|
Initializes the GradioTranscriptionInterface with a transcription model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model (Scraibe): Model responsible for audio transcription tasks.
|
||||||
|
"""
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
def auto_transcribe(self, source,
|
||||||
|
num_speakers : int,
|
||||||
|
translation : bool,
|
||||||
|
language : str):
|
||||||
|
"""
|
||||||
|
Shortcut method for the Scraibe task.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple: Transcribed text (str), JSON output (dict)
|
||||||
|
"""
|
||||||
|
|
||||||
|
kwargs = {
|
||||||
|
"num_speakers": num_speakers if num_speakers != 0 else None,
|
||||||
|
"language": language if language != "None" else None,
|
||||||
|
"task": 'translate' if translation else None
|
||||||
|
}
|
||||||
|
if isinstance(source, str):
|
||||||
|
try:
|
||||||
|
result = self.model.autotranscribe(source, **kwargs)
|
||||||
|
except ValueError:
|
||||||
|
raise gr.Error("Couldn't detect any speech in the provided audio. \
|
||||||
|
Please try again!")
|
||||||
|
|
||||||
|
return str(result), result.get_json()
|
||||||
|
|
||||||
|
elif isinstance(source, list):
|
||||||
|
source_names = [s.split("/")[-1] for s in source]
|
||||||
|
result = []
|
||||||
|
for s in tqdm(source, total=len(source),desc = "Transcribing audio files"):
|
||||||
|
try:
|
||||||
|
res = self.model.autotranscribe(s, **kwargs)
|
||||||
|
except ValueError:
|
||||||
|
_name = s.split("/")[-1]
|
||||||
|
res = f"NO TRANSCRIPT FOUND FOR {_name}"
|
||||||
|
gr.Warning(f"Couldn't detect any speech in {_name} will skip this file.")
|
||||||
|
result.append(res)
|
||||||
|
|
||||||
|
out = ''
|
||||||
|
out_dict = {}
|
||||||
|
for i, r in enumerate(result):
|
||||||
|
out += f"TRANSCRIPT {i} FOR ({source_names[i]}):\n\n"
|
||||||
|
out += str(r)
|
||||||
|
out += "\n\n"
|
||||||
|
|
||||||
|
if isinstance(r, str):
|
||||||
|
out_dict[source_names[i]] = r
|
||||||
|
else:
|
||||||
|
out_dict[source_names[i]] = r.get_dict()
|
||||||
|
|
||||||
|
return out, json.dumps(out_dict, indent=4)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise gr.Error("Please provide a valid audio file.")
|
||||||
|
|
||||||
|
|
||||||
|
def transcribe(self, source, translation, language):
|
||||||
|
"""
|
||||||
|
Shortcut method for the Transcribe task.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Transcribed text.
|
||||||
|
"""
|
||||||
|
kwargs = {
|
||||||
|
"language": language if language != "None" else None,
|
||||||
|
"task": 'translate' if translation == "Yes" else None
|
||||||
|
}
|
||||||
|
|
||||||
|
if isinstance(source, str):
|
||||||
|
result = self.model.transcribe(source, **kwargs)
|
||||||
|
|
||||||
|
return str(result)
|
||||||
|
|
||||||
|
elif isinstance(source, list):
|
||||||
|
source_names = [s.split("/")[-1] for s in source]
|
||||||
|
result = []
|
||||||
|
for s in tqdm(source, total=len(source),desc = "Transcribing audio files"):
|
||||||
|
res = self.model.transcribe(s, **kwargs)
|
||||||
|
result.append(res)
|
||||||
|
|
||||||
|
out = ''
|
||||||
|
for i, res in enumerate(result):
|
||||||
|
out += f"TRANSCRIPT {i} FOR ({source_names[i]}):\n\n"
|
||||||
|
out += str(res)
|
||||||
|
out += "\n\n"
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise gr.Error("Please provide a valid audio file.")
|
||||||
|
|
||||||
|
def perform_diarisation(self, source, num_speakers):
|
||||||
|
"""
|
||||||
|
Shortcut method for the Diarisation task.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: JSON output of diarisation result.
|
||||||
|
"""
|
||||||
|
kwargs = {
|
||||||
|
"num_speakers": num_speakers if num_speakers != 0 else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
if isinstance(source, str):
|
||||||
|
try:
|
||||||
|
result = self.model.diarization(source, **kwargs)
|
||||||
|
except ValueError:
|
||||||
|
raise gr.Error("Couldn't detect any speech in the provided audio. \
|
||||||
|
Please try again!")
|
||||||
|
|
||||||
|
return json.dumps(result, indent=2)
|
||||||
|
elif isinstance(source, list):
|
||||||
|
source_names = [s.split("/")[-1] for s in source]
|
||||||
|
result = []
|
||||||
|
for s in tqdm(source, total=len(source),desc = "Performing diarisation"):
|
||||||
|
try:
|
||||||
|
res = self.model.diarization(s, **kwargs)
|
||||||
|
except ValueError:
|
||||||
|
res = f"NO DIARISATION FOUND FOR {s}"
|
||||||
|
gr.Warning(f"Couldn't detect any speech in {s} will skip this file.")
|
||||||
|
result.append(res)
|
||||||
|
|
||||||
|
out = {}
|
||||||
|
|
||||||
|
for i, res in enumerate(result):
|
||||||
|
out[source_names[i]] = res
|
||||||
|
|
||||||
|
return json.dumps(out, indent=4)
|
||||||
|
|
||||||
|
else:
|
||||||
|
gr.Error("Please provide a valid audio file.")
|
||||||
|
|
||||||
|
|
||||||
|
####
|
||||||
|
# Gradio Interface
|
||||||
|
####
|
||||||
|
|
||||||
|
def gradio_Interface(model : Scraibe = None):
|
||||||
|
|
||||||
|
if model is None:
|
||||||
|
model = Scraibe()
|
||||||
|
|
||||||
|
pipe = GradioTranscriptionInterface(model)
|
||||||
|
|
||||||
|
def select_task(choice):
|
||||||
|
if choice == 'Auto Transcribe':
|
||||||
|
|
||||||
|
return (gr.update(visible = True),
|
||||||
|
gr.update(visible = True),
|
||||||
|
gr.update(visible = True))
|
||||||
|
|
||||||
|
|
||||||
|
elif choice == 'Transcribe':
|
||||||
|
|
||||||
|
return (gr.update(visible = False),
|
||||||
|
gr.update(visible = True),
|
||||||
|
gr.update(visible = True))
|
||||||
|
|
||||||
|
|
||||||
|
elif choice == 'Diarisation':
|
||||||
|
|
||||||
|
return (gr.update(visible = True),
|
||||||
|
gr.update(visible = False),
|
||||||
|
gr.update(visible = False))
|
||||||
|
|
||||||
|
def select_origin(choice):
|
||||||
|
if choice == "Upload Audio":
|
||||||
|
|
||||||
|
return (gr.update(visible = True),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None))
|
||||||
|
|
||||||
|
elif choice == "Record Audio":
|
||||||
|
|
||||||
|
return (gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = True),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None))
|
||||||
|
|
||||||
|
elif choice == "Upload Video":
|
||||||
|
|
||||||
|
return (gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = True),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None))
|
||||||
|
|
||||||
|
elif choice == "Record Video":
|
||||||
|
|
||||||
|
return (gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = True),
|
||||||
|
gr.update(visible = False, value = None))
|
||||||
|
|
||||||
|
elif choice == "File or Files":
|
||||||
|
|
||||||
|
return (gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = False, value = None),
|
||||||
|
gr.update(visible = True))
|
||||||
|
|
||||||
|
def run_scribe(task,
|
||||||
|
num_speakers,
|
||||||
|
translate,
|
||||||
|
language,
|
||||||
|
audio1,
|
||||||
|
audio2,
|
||||||
|
video1,
|
||||||
|
video2,
|
||||||
|
file_in,
|
||||||
|
progress = gr.Progress(track_tqdm= True)):
|
||||||
|
# get *args which are not None
|
||||||
|
progress(0, desc='Starting task...')
|
||||||
|
source = audio1 or audio2 or video1 or video2 or file_in
|
||||||
|
|
||||||
|
if isinstance(source, list):
|
||||||
|
source = [s.name for s in source]
|
||||||
|
if len(source) == 1:
|
||||||
|
source = source[0]
|
||||||
|
|
||||||
|
if task == 'Auto Transcribe':
|
||||||
|
|
||||||
|
out_str , out_json = pipe.auto_transcribe(source = source,
|
||||||
|
num_speakers = num_speakers,
|
||||||
|
translation = translate,
|
||||||
|
language = language)
|
||||||
|
|
||||||
|
if isinstance(source, str):
|
||||||
|
return (gr.update(value = out_str, visible = True),
|
||||||
|
gr.update(value = out_json, visible = True),
|
||||||
|
gr.update(visible = True),
|
||||||
|
gr.update(visible = True))
|
||||||
|
else:
|
||||||
|
return (gr.update(value = out_str, visible = True),
|
||||||
|
gr.update(value = out_json, visible = True),
|
||||||
|
gr.update(visible = False),
|
||||||
|
gr.update(visible = False))
|
||||||
|
|
||||||
|
elif task == 'Transcribe':
|
||||||
|
|
||||||
|
out = pipe.transcribe(source = source,
|
||||||
|
translation = translate,
|
||||||
|
language = language)
|
||||||
|
|
||||||
|
return (gr.update(value = out, visible = True),
|
||||||
|
gr.update(value = None, visible = False),
|
||||||
|
gr.update(visible = False),
|
||||||
|
gr.update(visible = False))
|
||||||
|
|
||||||
|
elif task == 'Diarisation':
|
||||||
|
|
||||||
|
out = pipe.perform_diarisation(source = source,
|
||||||
|
num_speakers = num_speakers)
|
||||||
|
|
||||||
|
return (gr.update(value = None, visible = False),
|
||||||
|
gr.update(value = out, visible = True),
|
||||||
|
gr.update(visible = False),
|
||||||
|
gr.update(visible = False))
|
||||||
|
|
||||||
|
def annotate_output(annoation : str, out_json : dict):
|
||||||
|
# get *args which are not None
|
||||||
|
|
||||||
|
trans = Transcript.from_json(out_json)
|
||||||
|
trans = trans.annotate(*annoation.split(","))
|
||||||
|
|
||||||
|
return gr.update(value = str(trans)),gr.update(value = trans.get_json())
|
||||||
|
|
||||||
|
|
||||||
|
with gr.Blocks(theme=theme,title='ScrAIbe: Automatic Audio Transcription') as demo:
|
||||||
|
|
||||||
|
# Define components
|
||||||
|
hname = os.path.join(CURRENT_PATH, "header.html")
|
||||||
|
header = open(hname, "r").read()
|
||||||
|
gr.HTML(header, visible= True, show_label=False)
|
||||||
|
|
||||||
|
with gr.Row():
|
||||||
|
|
||||||
|
with gr.Column():
|
||||||
|
|
||||||
|
task = gr.Radio(["Auto Transcribe", "Transcribe", "Diarisation"], label="Task",
|
||||||
|
value= 'Auto Transcribe')
|
||||||
|
|
||||||
|
num_speakers = gr.Number(value=0, label= "Number of speakers (optional)",
|
||||||
|
info = "Number of speakers in the audio file. If you don't know,\
|
||||||
|
leave it at 0.", visible= True)
|
||||||
|
|
||||||
|
translate = gr.Checkbox(label="Translation", choices=[True, False], value = False,
|
||||||
|
info="Select 'Yes' to have the output translated into English.",
|
||||||
|
visible= True)
|
||||||
|
|
||||||
|
language = gr.Dropdown(LANGUAGES,
|
||||||
|
label="Language (optional)", value = "None",
|
||||||
|
info="Language of the audio file. If you don't know,\
|
||||||
|
leave it at None.", visible= True)
|
||||||
|
|
||||||
|
input = gr.Radio(["Upload Audio", "Record Audio", "Upload Video","Record Video"
|
||||||
|
,"File or Files"], label="Input Type", value="Upload Audio")
|
||||||
|
|
||||||
|
audio1 = gr.Audio(source="upload", type="filepath", label="Upload Audio",
|
||||||
|
interactive= True, visible= True)
|
||||||
|
audio2 = gr.Audio(source="microphone", label="Record Audio", type="filepath",
|
||||||
|
interactive= True, visible= False)
|
||||||
|
video1 = gr.Video(source="upload", type="filepath", label="Upload Video",
|
||||||
|
interactive= True, visible= False)
|
||||||
|
video2 = gr.Video(source="webcam", label="Record Video", type="filepath",
|
||||||
|
interactive= True, visible= False)
|
||||||
|
file_in = gr.Files(label="Upload File or Files", interactive= True, visible= False)
|
||||||
|
|
||||||
|
submit = gr.Button()
|
||||||
|
|
||||||
|
with gr.Column():
|
||||||
|
|
||||||
|
out_txt = gr.Textbox(label="Output",
|
||||||
|
visible= True, show_copy_button=True)
|
||||||
|
|
||||||
|
out_json = gr.JSON(label="JSON Output",
|
||||||
|
visible= False, show_copy_button=True)
|
||||||
|
|
||||||
|
annoation = gr.Textbox(label="Name your speaker's",
|
||||||
|
info= "Please provide a list of the speakers arranged \
|
||||||
|
in the order in which they appear in the input. Use comma ',' \
|
||||||
|
as a seperator. Be aware that the first name is given \
|
||||||
|
to SPEAKER_00 the second to SPEAKER_01 and so on.",
|
||||||
|
visible= False, interactive= True)
|
||||||
|
|
||||||
|
annotate = gr.Button(value="Annotate", visible= False, interactive= True)
|
||||||
|
|
||||||
|
# Define usage of components
|
||||||
|
input.change(fn=select_origin, inputs=[input],
|
||||||
|
outputs=[audio1, audio2, video1, video2, file_in])
|
||||||
|
|
||||||
|
task.change(fn=select_task, inputs=[task],
|
||||||
|
outputs=[num_speakers, translate, language])
|
||||||
|
|
||||||
|
translate.change(fn= lambda x : gr.update(value = x),
|
||||||
|
inputs=[translate], outputs=[translate])
|
||||||
|
num_speakers.change(fn= lambda x : gr.update(value = x),
|
||||||
|
inputs=[num_speakers], outputs=[num_speakers])
|
||||||
|
language.change(fn= lambda x : gr.update(value = x),
|
||||||
|
inputs=[language], outputs=[language])
|
||||||
|
|
||||||
|
submit.click(fn = run_scribe,
|
||||||
|
inputs=[task, num_speakers, translate, language, audio1,
|
||||||
|
audio2, video1, video2, file_in],
|
||||||
|
outputs=[out_txt, out_json, annoation, annotate])
|
||||||
|
|
||||||
|
annotate.click(fn = annotate_output, inputs=[annoation, out_json],
|
||||||
|
outputs=[out_txt, out_json])
|
||||||
|
|
||||||
|
return demo
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
gradio_Interface().queue().launch()
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<!-- Importing Cormorant Garamond font from Google Fonts -->
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;700&display=swap" rel="stylesheet">
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.header-container {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
position: relative;
|
||||||
|
padding-top: 30px;
|
||||||
|
}
|
||||||
|
.logo-container {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
right: 20px;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 300px;
|
||||||
|
}
|
||||||
|
.logo {
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-family: 'Cormorant Garamond', serif;
|
||||||
|
font-size: 50px !important; /* Increased font size */
|
||||||
|
font-weight: bold;
|
||||||
|
color: #50AF31;
|
||||||
|
margin: 0;
|
||||||
|
position: relative;
|
||||||
|
padding: 0.5em 0;
|
||||||
|
}
|
||||||
|
h1::before, h1::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
height: 2px;
|
||||||
|
width: 80%;
|
||||||
|
background-color: #50AF31;
|
||||||
|
left: 10%;
|
||||||
|
}
|
||||||
|
h1::before {
|
||||||
|
top: 0.5em;
|
||||||
|
}
|
||||||
|
h1::after {
|
||||||
|
bottom: 0.5em;
|
||||||
|
}
|
||||||
|
p, h2 {
|
||||||
|
font-size: 16px;
|
||||||
|
margin: 10px 0;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<div class="header-container">
|
||||||
|
<h1>ScrAIbe</h1>
|
||||||
|
<div class="logo-container">
|
||||||
|
<a href="https://www.kida-bmel.de/"> <!-- Replace with your actual URL -->
|
||||||
|
<img src="file/Logo_KIDA_bmel_green.svg" alt="KIDA Logo" class="logo">
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="text-align: center; padding: 20px 10%;">
|
||||||
|
<p>
|
||||||
|
Upload, record, or provide a video with audio for transcription. Our toolkit is designed to transcribe content from multiple languages accurately. The integrated speaker diarisation feature identifies different speakers, ensuring a smooth transcription experience. For optimal results, indicate the number of speakers and the original language of the content.
|
||||||
|
</p>
|
||||||
|
<h2 style="font-weight: bold; color: #50AF31;">What would you like to do next?</h2>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
"""
|
||||||
|
This file contains a modified version of qtfaststart by qtfaststart
|
||||||
|
https://github.com/danielgtaylor/qtfaststart/tree/master
|
||||||
|
|
||||||
|
All credit goes to the original author.
|
||||||
|
Copyright (C) 2008 - 2013 Daniel G. Taylor <dan@programmer-art.org>
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
||||||
|
software and associated documentation files (the "Software"),
|
||||||
|
to deal in the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||||
|
Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all copies
|
||||||
|
or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||||
|
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||||
|
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||||
|
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||||
|
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||||
|
IN THE SOFTWARE.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import collections
|
||||||
|
import io
|
||||||
|
|
||||||
|
# define error classes
|
||||||
|
class FastStartException(Exception):
|
||||||
|
"""
|
||||||
|
Raised when something bad happens during processing.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class FastStartSetupError(FastStartException):
|
||||||
|
"""
|
||||||
|
Rasised when asked to process a file that does not need processing
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class MalformedFileError(FastStartException):
|
||||||
|
"""
|
||||||
|
Raised when the input file is setup in an unexpected way
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class UnsupportedFormatError(FastStartException):
|
||||||
|
"""
|
||||||
|
Raised when a movie file is recognized as a format not supported.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
# define constants
|
||||||
|
CHUNK_SIZE = 8192
|
||||||
|
|
||||||
|
log = logging.getLogger("qtfaststart")
|
||||||
|
|
||||||
|
# Older versions of Python require this to be defined
|
||||||
|
if not hasattr(os, 'SEEK_CUR'):
|
||||||
|
os.SEEK_CUR = 1
|
||||||
|
|
||||||
|
Atom = collections.namedtuple('Atom', 'name position size')
|
||||||
|
|
||||||
|
def read_atom(datastream):
|
||||||
|
"""
|
||||||
|
Read an atom and return a tuple of (size, type) where size is the size
|
||||||
|
in bytes (including the 8 bytes already read) and type is a "fourcc"
|
||||||
|
like "ftyp" or "moov".
|
||||||
|
"""
|
||||||
|
size, type = struct.unpack(">L4s", datastream.read(8))
|
||||||
|
type = type.decode('ascii')
|
||||||
|
return size, type
|
||||||
|
|
||||||
|
|
||||||
|
def _read_atom_ex(datastream):
|
||||||
|
"""
|
||||||
|
Read an Atom from datastream
|
||||||
|
"""
|
||||||
|
pos = datastream.tell()
|
||||||
|
atom_size, atom_type = read_atom(datastream)
|
||||||
|
if atom_size == 1:
|
||||||
|
atom_size, = struct.unpack(">Q", datastream.read(8))
|
||||||
|
return Atom(atom_type, pos, atom_size)
|
||||||
|
|
||||||
|
|
||||||
|
def get_index(datastream):
|
||||||
|
"""
|
||||||
|
Return an index of top level atoms, their absolute byte-position in the
|
||||||
|
file and their size in a list:
|
||||||
|
|
||||||
|
index = [
|
||||||
|
("ftyp", 0, 24),
|
||||||
|
("moov", 25, 2658),
|
||||||
|
("free", 2683, 8),
|
||||||
|
...
|
||||||
|
]
|
||||||
|
|
||||||
|
The tuple elements will be in the order that they appear in the file.
|
||||||
|
"""
|
||||||
|
log.debug("Getting index of top level atoms...")
|
||||||
|
|
||||||
|
index = list(_read_atoms(datastream))
|
||||||
|
_ensure_valid_index(index)
|
||||||
|
|
||||||
|
return index
|
||||||
|
|
||||||
|
|
||||||
|
def _read_atoms(datastream):
|
||||||
|
"""
|
||||||
|
Read atoms until an error occurs
|
||||||
|
"""
|
||||||
|
while datastream:
|
||||||
|
try:
|
||||||
|
atom = _read_atom_ex(datastream)
|
||||||
|
log.debug("%s: %s" % (atom.name, atom.size))
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
|
||||||
|
yield atom
|
||||||
|
|
||||||
|
if atom.size == 0:
|
||||||
|
if atom.name == "mdat":
|
||||||
|
# Some files may end in mdat with no size set, which generally
|
||||||
|
# means to seek to the end of the file. We can just stop indexing
|
||||||
|
# as no more entries will be found!
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# Weird, but just continue to try to find more atoms
|
||||||
|
continue
|
||||||
|
|
||||||
|
datastream.seek(atom.position + atom.size)
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_valid_index(index):
|
||||||
|
"""
|
||||||
|
Ensure the minimum viable atoms are present in the index.
|
||||||
|
|
||||||
|
Raise FastStartException if not.
|
||||||
|
"""
|
||||||
|
top_level_atoms = set([item.name for item in index])
|
||||||
|
for key in ["moov", "mdat"]:
|
||||||
|
if key not in top_level_atoms:
|
||||||
|
log.error("%s atom not found, is this a valid MOV/MP4 file?" % key)
|
||||||
|
raise FastStartException()
|
||||||
|
|
||||||
|
|
||||||
|
def find_atoms(size, datastream):
|
||||||
|
"""
|
||||||
|
Compatibilty interface for _find_atoms_ex
|
||||||
|
"""
|
||||||
|
fake_parent = Atom('fake', datastream.tell()-8, size+8)
|
||||||
|
for atom in _find_atoms_ex(fake_parent, datastream):
|
||||||
|
yield atom.name
|
||||||
|
|
||||||
|
|
||||||
|
def _find_atoms_ex(parent_atom, datastream):
|
||||||
|
"""
|
||||||
|
Yield either "stco" or "co64" Atoms from datastream.
|
||||||
|
datastream will be 8 bytes into the stco or co64 atom when the value
|
||||||
|
is yielded.
|
||||||
|
|
||||||
|
It is assumed that datastream will be at the end of the atom after
|
||||||
|
the value has been yielded and processed.
|
||||||
|
|
||||||
|
parent_atom is the parent atom, a 'moov' or other ancestor of CO
|
||||||
|
atoms in the datastream.
|
||||||
|
"""
|
||||||
|
stop = parent_atom.position + parent_atom.size
|
||||||
|
|
||||||
|
while datastream.tell() < stop:
|
||||||
|
try:
|
||||||
|
atom = _read_atom_ex(datastream)
|
||||||
|
except:
|
||||||
|
log.exception("Error reading next atom!")
|
||||||
|
raise FastStartException()
|
||||||
|
|
||||||
|
if atom.name in ["trak", "mdia", "minf", "stbl"]:
|
||||||
|
# Known ancestor atom of stco or co64, search within it!
|
||||||
|
for res in _find_atoms_ex(atom, datastream):
|
||||||
|
yield res
|
||||||
|
elif atom.name in ["stco", "co64"]:
|
||||||
|
yield atom
|
||||||
|
else:
|
||||||
|
# Ignore this atom, seek to the end of it.
|
||||||
|
datastream.seek(atom.position + atom.size)
|
||||||
|
|
||||||
|
|
||||||
|
def process(infilename, limit=float('inf')):
|
||||||
|
"""
|
||||||
|
Convert a Quicktime/MP4 file for streaming by moving the metadata to
|
||||||
|
the front of the file. This method writes a new file.
|
||||||
|
|
||||||
|
If limit is set to something other than zero it will be used as the
|
||||||
|
number of bytes to write of the atoms following the moov atom. This
|
||||||
|
is very useful to create a small sample of a file with full headers,
|
||||||
|
which can then be used in bug reports and such.
|
||||||
|
"""
|
||||||
|
if isinstance(infilename, str):
|
||||||
|
datastream = open(infilename, "rb")
|
||||||
|
elif isinstance(infilename, bytes):
|
||||||
|
datastream = io.BytesIO(infilename)
|
||||||
|
else:
|
||||||
|
raise TypeError("infilename must be a filename, bytes or file-like object")
|
||||||
|
# Get the top level atom index
|
||||||
|
index = get_index(datastream)
|
||||||
|
|
||||||
|
mdat_pos = 999999
|
||||||
|
free_size = 0
|
||||||
|
|
||||||
|
# Make sure moov occurs AFTER mdat, otherwise no need to run!
|
||||||
|
for atom in index:
|
||||||
|
# The atoms are guaranteed to exist from get_index above!
|
||||||
|
if atom.name == "moov":
|
||||||
|
moov_atom = atom
|
||||||
|
moov_pos = atom.position
|
||||||
|
elif atom.name == "mdat":
|
||||||
|
mdat_pos = atom.position
|
||||||
|
elif atom.name == "free" and atom.position < mdat_pos:
|
||||||
|
# This free atom is before the mdat!
|
||||||
|
free_size += atom.size
|
||||||
|
log.info("Removing free atom at %d (%d bytes)" % (atom.position, atom.size))
|
||||||
|
elif atom.name == "\x00\x00\x00\x00" and atom.position < mdat_pos:
|
||||||
|
# This is some strange zero atom with incorrect size
|
||||||
|
free_size += 8
|
||||||
|
log.info("Removing strange zero atom at %s (8 bytes)" % atom.position)
|
||||||
|
|
||||||
|
# Offset to shift positions
|
||||||
|
offset = moov_atom.size - free_size
|
||||||
|
|
||||||
|
if moov_pos < mdat_pos:
|
||||||
|
# moov appears to be in the proper place, don't shift by moov size
|
||||||
|
offset -= moov_atom.size
|
||||||
|
if not free_size:
|
||||||
|
# No free atoms and moov is correct, we are done!
|
||||||
|
log.error("This file appears to already be setup for streaming!")
|
||||||
|
# Stupid hack to retrun the non-processed file:
|
||||||
|
if isinstance(infilename, str):
|
||||||
|
return open(infilename, "rb").read()
|
||||||
|
elif isinstance(infilename, bytes):
|
||||||
|
return io.BytesIO(infilename).read()
|
||||||
|
|
||||||
|
# Read and fix moov
|
||||||
|
moov = _patch_moov(datastream, moov_atom, offset)
|
||||||
|
|
||||||
|
log.info("Writing output...")
|
||||||
|
outfile = b''
|
||||||
|
|
||||||
|
# Write ftype
|
||||||
|
for atom in index:
|
||||||
|
if atom.name == "ftyp":
|
||||||
|
log.debug("Writing ftyp... (%d bytes)" % atom.size)
|
||||||
|
datastream.seek(atom.position)
|
||||||
|
outfile += datastream.read(atom.size)
|
||||||
|
|
||||||
|
# Write moov
|
||||||
|
_bytes = moov.getvalue()
|
||||||
|
log.debug("Writing moov... (%d bytes)" % len(_bytes))
|
||||||
|
outfile += _bytes
|
||||||
|
|
||||||
|
# Write the rest
|
||||||
|
atoms = [item for item in index if item.name not in ["ftyp", "moov", "free"]]
|
||||||
|
for atom in atoms:
|
||||||
|
log.debug("Writing %s... (%d bytes)" % (atom.name, atom.size))
|
||||||
|
datastream.seek(atom.position)
|
||||||
|
|
||||||
|
# for compatability, allow '0' to mean no limit
|
||||||
|
cur_limit = limit or float('inf')
|
||||||
|
cur_limit = min(cur_limit, atom.size)
|
||||||
|
|
||||||
|
for chunk in get_chunks(datastream, CHUNK_SIZE, cur_limit):
|
||||||
|
outfile += chunk
|
||||||
|
|
||||||
|
return outfile
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_moov(datastream, atom, offset):
|
||||||
|
datastream.seek(atom.position)
|
||||||
|
moov = io.BytesIO(datastream.read(atom.size))
|
||||||
|
|
||||||
|
# reload the atom from the fixed stream
|
||||||
|
atom = _read_atom_ex(moov)
|
||||||
|
|
||||||
|
for atom in _find_atoms_ex(atom, moov):
|
||||||
|
# Read either 32-bit or 64-bit offsets
|
||||||
|
ctype, csize = dict(
|
||||||
|
stco=('L', 4),
|
||||||
|
co64=('Q', 8),
|
||||||
|
)[atom.name]
|
||||||
|
|
||||||
|
# Get number of entries
|
||||||
|
version, entry_count = struct.unpack(">2L", moov.read(8))
|
||||||
|
|
||||||
|
log.info("Patching %s with %d entries" % (atom.name, entry_count))
|
||||||
|
|
||||||
|
entries_pos = moov.tell()
|
||||||
|
|
||||||
|
struct_fmt = ">%(entry_count)s%(ctype)s" % vars()
|
||||||
|
|
||||||
|
# Read entries
|
||||||
|
entries = struct.unpack(struct_fmt, moov.read(csize * entry_count))
|
||||||
|
|
||||||
|
# Patch and write entries
|
||||||
|
offset_entries = [entry + offset for entry in entries]
|
||||||
|
moov.seek(entries_pos)
|
||||||
|
moov.write(struct.pack(struct_fmt, *offset_entries))
|
||||||
|
return moov
|
||||||
|
|
||||||
|
def get_chunks(stream, chunk_size, limit):
|
||||||
|
remaining = limit
|
||||||
|
while remaining:
|
||||||
|
chunk = stream.read(min(remaining, chunk_size))
|
||||||
|
if not chunk:
|
||||||
|
return
|
||||||
|
remaining -= len(chunk)
|
||||||
|
yield chunk
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
"""
|
||||||
|
Audio Processor Module
|
||||||
|
=======================
|
||||||
|
|
||||||
|
This module provides the AudioProcessor class, utilizing PyTorchaudio for handling audio files.
|
||||||
|
It includes functionalities to load, cut, and manage audio waveforms, offering efficient and
|
||||||
|
flexible audio processing.
|
||||||
|
|
||||||
|
Available Classes:
|
||||||
|
- AudioProcessor: Processes audio waveforms and provides methods for loading,
|
||||||
|
cutting, and handling audio.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from .audio_import AudioProcessor
|
||||||
|
|
||||||
|
processor = AudioProcessor.from_file("path/to/audiofile.wav")
|
||||||
|
cut_waveform = processor.cut(start=1.0, end=5.0)
|
||||||
|
|
||||||
|
Constants:
|
||||||
|
- SAMPLE_RATE (int): Default sample rate for processing.
|
||||||
|
- NORMALIZATION_FACTOR (float): Normalization factor for audio waveform.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from subprocess import CalledProcessError, run
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
|
||||||
|
SAMPLE_RATE = 16000
|
||||||
|
NORMALIZATION_FACTOR = 32768.0
|
||||||
|
|
||||||
|
class AudioProcessor:
|
||||||
|
"""
|
||||||
|
Audio Processor class that leverages PyTorchaudio to provide functionalities
|
||||||
|
for loading, cutting, and handling audio waveforms.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
waveform: torch.Tensor
|
||||||
|
The audio waveform tensor.
|
||||||
|
sr: int
|
||||||
|
The sample rate of the audio.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, waveform: torch.Tensor, sr : int = SAMPLE_RATE,
|
||||||
|
*args, **kwargs) -> None:
|
||||||
|
|
||||||
|
"""
|
||||||
|
Initialize the AudioProcessor object.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
waveform (torch.Tensor): The audio waveform tensor.
|
||||||
|
sr (int, optional): The sample rate of the audio. Defaults to SAMPLE_RATE.
|
||||||
|
args: Additional arguments.
|
||||||
|
kwargs: Additional keyword arguments, e.g., device to use for processing.
|
||||||
|
If CUDA is available, it defaults to CUDA.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If the provided sample rate is not of type int.
|
||||||
|
"""
|
||||||
|
|
||||||
|
device = kwargs.get("device", "cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
|
||||||
|
self.waveform = waveform.to(device)
|
||||||
|
self.sr = sr
|
||||||
|
|
||||||
|
if not isinstance(self.sr, int):
|
||||||
|
raise ValueError("Sample rate should be a single value of type int," \
|
||||||
|
f"not {len(self.sr)} and type {type(self.sr)}")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_file(cls, file: str, *args, **kwargs) -> 'AudioProcessor':
|
||||||
|
"""
|
||||||
|
Create an AudioProcessor instance from an audio file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file (str): The audio file path.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
AudioProcessor: An instance of the AudioProcessor class containing the loaded audio.
|
||||||
|
"""
|
||||||
|
|
||||||
|
audio, sr = cls.load_audio(file , *args, **kwargs)
|
||||||
|
|
||||||
|
audio = torch.from_numpy(audio)
|
||||||
|
|
||||||
|
return cls(audio, sr)
|
||||||
|
|
||||||
|
|
||||||
|
def cut(self, start: float, end: float) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Cut a segment from the audio waveform between the specified start and end times.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
start (float): Start time in seconds.
|
||||||
|
end (float): End time in seconds.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
torch.Tensor: The cut waveform segment.
|
||||||
|
"""
|
||||||
|
|
||||||
|
start = int(start * self.sr)
|
||||||
|
if (isinstance(end, float) or isinstance(end, int)) and isinstance(self.sr, int):
|
||||||
|
end = int(np.ceil(end * self.sr))
|
||||||
|
else:
|
||||||
|
end = int(torch.ceil(end * self.sr))
|
||||||
|
return self.waveform[start:end]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def load_audio(file: str, sr: int = SAMPLE_RATE):
|
||||||
|
"""
|
||||||
|
Open an audio file and read it as a mono waveform, resampling if necessary.
|
||||||
|
This method ensures compatibility with pyannote.audio
|
||||||
|
and requires the ffmpeg CLI in PATH.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file (str): The audio file to open.
|
||||||
|
sr (int, optional): The desired sample rate. Defaults to SAMPLE_RATE.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple: A NumPy array containing the audio waveform in float32 dtype
|
||||||
|
and the sample rate.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: If failed to load audio.
|
||||||
|
"""
|
||||||
|
# This launches a subprocess to decode audio while down-mixing
|
||||||
|
# and resampling as necessary. Requires the ffmpeg CLI in PATH.
|
||||||
|
# fmt: off
|
||||||
|
cmd = [
|
||||||
|
"ffmpeg",
|
||||||
|
"-nostdin",
|
||||||
|
"-threads", "0",
|
||||||
|
"-i", file,
|
||||||
|
"-f", "s16le",
|
||||||
|
"-ac", "1",
|
||||||
|
"-acodec", "pcm_s16le",
|
||||||
|
"-ar", str(sr),
|
||||||
|
"-"
|
||||||
|
]
|
||||||
|
# fmt: on
|
||||||
|
try:
|
||||||
|
out = run(cmd, capture_output=True, check=True).stdout
|
||||||
|
except CalledProcessError as e:
|
||||||
|
raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
|
||||||
|
|
||||||
|
out = np.frombuffer(out, np.int16).flatten().astype(np.float32) / NORMALIZATION_FACTOR
|
||||||
|
|
||||||
|
return out , sr
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f'TorchAudioProcessor(waveform={len(self.waveform)}, sr={int(self.sr)})'
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
"""
|
||||||
|
Scraibe Class
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
This class serves as the core of the transcription system, responsible for handling
|
||||||
|
transcription and diarization of audio files. It leverages pretrained models for
|
||||||
|
speech-to-text (such as Whisper) and speaker diarization (such as pyannote.audio),
|
||||||
|
providing an accessible interface for audio processing tasks such as transcription,
|
||||||
|
speaker separation, and timestamping.
|
||||||
|
|
||||||
|
By encapsulating the complexities of underlying models, it allows for straightforward
|
||||||
|
integration into various applications, ranging from transcription services to voice assistants.
|
||||||
|
|
||||||
|
Available Classes:
|
||||||
|
- Scraibe: Main class for performing transcription and diarization.
|
||||||
|
Includes methods for loading models, processing audio files,
|
||||||
|
and formatting the transcription output.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from scraibe import Scraibe
|
||||||
|
|
||||||
|
model = Scraibe()
|
||||||
|
transcript = model.autotranscribe("path/to/audiofile.wav")
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Standard Library Imports
|
||||||
|
import os
|
||||||
|
from glob import iglob
|
||||||
|
from subprocess import run
|
||||||
|
from typing import TypeVar, Union
|
||||||
|
from warnings import warn
|
||||||
|
|
||||||
|
# Third-Party Imports
|
||||||
|
import torch
|
||||||
|
from numpy import ndarray
|
||||||
|
from tqdm import trange
|
||||||
|
|
||||||
|
# Application-Specific Imports
|
||||||
|
from .audio import AudioProcessor
|
||||||
|
from .diarisation import Diariser
|
||||||
|
from .transcriber import Transcriber, whisper
|
||||||
|
from .transcript_exporter import Transcript
|
||||||
|
|
||||||
|
|
||||||
|
DiarisationType = TypeVar('DiarisationType')
|
||||||
|
|
||||||
|
|
||||||
|
class Scraibe:
|
||||||
|
"""
|
||||||
|
Scraibe is a class responsible for managing the transcription and diarization of audio files.
|
||||||
|
It serves as the core of the transcription system, incorporating pretrained models
|
||||||
|
for speech-to-text (such as Whisper) and speaker diarization (such as pyannote.audio),
|
||||||
|
allowing for comprehensive audio processing.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
transcriber (Transcriber): The transcriber object to handle transcription.
|
||||||
|
diariser (Diariser): The diariser object to handle diarization.
|
||||||
|
|
||||||
|
Methods:
|
||||||
|
__init__: Initializes the Scraibe class with appropriate models.
|
||||||
|
transcribe: Transcribes an audio file using the whisper model and pyannote diarization model.
|
||||||
|
remove_audio_file: Removes the original audio file to avoid disk space issues or ensure data privacy.
|
||||||
|
get_audio_file: Gets an audio file as an AudioProcessor object.
|
||||||
|
"""
|
||||||
|
def __init__(self,
|
||||||
|
whisper_model: Union[bool, str, whisper] = None,
|
||||||
|
dia_model : Union[bool, str, DiarisationType] = None,
|
||||||
|
**kwargs) -> None:
|
||||||
|
"""Initializes the Scraibe class.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
whisper_model (Union[bool, str, whisper], optional):
|
||||||
|
Path to whisper model or whisper model itself.
|
||||||
|
diarisation_model (Union[bool, str, DiarisationType], optional):
|
||||||
|
Path to pyannote diarization model or model itself.
|
||||||
|
**kwargs: Additional keyword arguments for whisper
|
||||||
|
and pyannote diarization models.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
if whisper_model is None:
|
||||||
|
self.transcriber = Transcriber.load_model("medium", **kwargs)
|
||||||
|
elif isinstance(whisper_model, str):
|
||||||
|
self.transcriber = Transcriber.load_model(whisper_model, **kwargs)
|
||||||
|
else:
|
||||||
|
self.transcriber = whisper_model
|
||||||
|
|
||||||
|
if dia_model is None:
|
||||||
|
self.diariser = Diariser.load_model(**kwargs)
|
||||||
|
elif isinstance(dia_model, str):
|
||||||
|
self.diariser = Diariser.load_model(dia_model, **kwargs)
|
||||||
|
else:
|
||||||
|
self.diariser = dia_model
|
||||||
|
|
||||||
|
if kwargs.get("verbose"):
|
||||||
|
print("Scraibe initialized all models successfully loaded.")
|
||||||
|
self.verbose = True
|
||||||
|
else:
|
||||||
|
self.verbose = False
|
||||||
|
|
||||||
|
def autotranscribe(self, audio_file : Union[str, torch.Tensor, ndarray],
|
||||||
|
remove_original : bool = False,
|
||||||
|
**kwargs) -> Transcript:
|
||||||
|
"""
|
||||||
|
Transcribes an audio file using the whisper model and pyannote diarization model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_file (Union[str, torch.Tensor, ndarray]):
|
||||||
|
Path to audio file or a tensor representing the audio.
|
||||||
|
remove_original (bool, optional): If True, the original audio file will
|
||||||
|
be removed after transcription.
|
||||||
|
*args: Additional positional arguments for diarization and transcription.
|
||||||
|
**kwargs: Additional keyword arguments for diarization and transcription.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Transcript: A Transcript object containing the transcription,
|
||||||
|
which can be exported to different formats.
|
||||||
|
"""
|
||||||
|
if kwargs.get("verbose"):
|
||||||
|
self.verbose = kwargs.get("verbose")
|
||||||
|
# Get audio file as an AudioProcessor object
|
||||||
|
audio_file = self.get_audio_file(audio_file)
|
||||||
|
|
||||||
|
# Prepare waveform and sample rate for diarization
|
||||||
|
dia_audio = {
|
||||||
|
"waveform" : audio_file.waveform.reshape(1,len(audio_file.waveform)),
|
||||||
|
"sample_rate": audio_file.sr
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.verbose:
|
||||||
|
print("Starting diarisation.")
|
||||||
|
|
||||||
|
diarisation = self.diariser.diarization(dia_audio, **kwargs)
|
||||||
|
|
||||||
|
if not diarisation["segments"]:
|
||||||
|
print("No segments found. Try to run transcription without diarisation.")
|
||||||
|
|
||||||
|
transcript = self.transcriber.transcribe(audio_file.waveform, **kwargs)
|
||||||
|
|
||||||
|
final_transcript= {0 : {"speakers" : 'SPEAKER_01',
|
||||||
|
"segments" : [0, len(audio_file.waveform)],
|
||||||
|
"text" : transcript}}
|
||||||
|
|
||||||
|
return Transcript(final_transcript)
|
||||||
|
|
||||||
|
if self.verbose:
|
||||||
|
print("Diarisation finished. Starting transcription.")
|
||||||
|
|
||||||
|
audio_file.sr = torch.Tensor([audio_file.sr]).to(audio_file.waveform.device)
|
||||||
|
|
||||||
|
# Transcribe each segment and store the results
|
||||||
|
final_transcript = dict()
|
||||||
|
|
||||||
|
for i in trange(len(diarisation["segments"]), desc= "Transcribing", disable = not self.verbose):
|
||||||
|
|
||||||
|
seg = diarisation["segments"][i]
|
||||||
|
|
||||||
|
audio = audio_file.cut(seg[0], seg[1])
|
||||||
|
|
||||||
|
transcript = self.transcriber.transcribe(audio, **kwargs)
|
||||||
|
|
||||||
|
final_transcript[i] = {"speakers" : diarisation["speakers"][i],
|
||||||
|
"segments" : seg,
|
||||||
|
"text" : transcript}
|
||||||
|
|
||||||
|
# Remove original file if needed
|
||||||
|
if remove_original:
|
||||||
|
if kwargs.get("shred") is True:
|
||||||
|
self.remove_audio_file(audio_file, shred=True)
|
||||||
|
else:
|
||||||
|
self.remove_audio_file(audio_file, shred=False)
|
||||||
|
|
||||||
|
return Transcript(final_transcript)
|
||||||
|
|
||||||
|
def diarization(self, audio_file : Union[str, torch.Tensor, ndarray],
|
||||||
|
**kwargs) -> dict:
|
||||||
|
"""
|
||||||
|
Perform diarization on an audio file using the pyannote diarization model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_file (Union[str, torch.Tensor, ndarray]):
|
||||||
|
The audio source which can either be a path to the audio file or a tensor representation.
|
||||||
|
**kwargs:
|
||||||
|
Additional keyword arguments for diarization.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict:
|
||||||
|
A dictionary containing the results of the diarization process.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Get audio file as an AudioProcessor object
|
||||||
|
audio_file = self.get_audio_file(audio_file)
|
||||||
|
|
||||||
|
# Prepare waveform and sample rate for diarization
|
||||||
|
dia_audio = {
|
||||||
|
"waveform" : audio_file.waveform.reshape(1,len(audio_file.waveform)),
|
||||||
|
"sample_rate": audio_file.sr
|
||||||
|
}
|
||||||
|
|
||||||
|
print("Starting diarisation.")
|
||||||
|
|
||||||
|
diarisation = self.diariser.diarization(dia_audio, **kwargs)
|
||||||
|
|
||||||
|
return diarisation
|
||||||
|
|
||||||
|
def transcribe(self, audio_file : Union[str, torch.Tensor, ndarray],
|
||||||
|
**kwargs):
|
||||||
|
"""
|
||||||
|
Transcribe the provided audio file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_file (Union[str, torch.Tensor, ndarray]):
|
||||||
|
The audio source, which can either be a path or a tensor representation.
|
||||||
|
**kwargs:
|
||||||
|
Additional keyword arguments for transcription.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str:
|
||||||
|
The transcribed text from the audio source.
|
||||||
|
"""
|
||||||
|
audio_file = self.get_audio_file(audio_file)
|
||||||
|
|
||||||
|
return self.transcriber.transcribe(audio_file.waveform, **kwargs)
|
||||||
|
@staticmethod
|
||||||
|
def remove_audio_file(audio_file : str,
|
||||||
|
shred : bool = False) -> None:
|
||||||
|
"""
|
||||||
|
Removes the original audio file to avoid disk space issues or ensure data privacy.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_file_path (str): Path to the audio file.
|
||||||
|
shred (bool, optional): If True, the audio file will be shredded,
|
||||||
|
not just removed.
|
||||||
|
"""
|
||||||
|
if not os.path.exists(audio_file):
|
||||||
|
raise ValueError(f"Audiofile {audio_file} does not exist.")
|
||||||
|
|
||||||
|
if shred:
|
||||||
|
|
||||||
|
warn("Shredding audiofile can take a long time.", RuntimeWarning)
|
||||||
|
|
||||||
|
gen = iglob(f'{audio_file}', recursive=True)
|
||||||
|
cmd = ['shred', '-zvu', '-n', '10', f'{audio_file}']
|
||||||
|
|
||||||
|
if os.path.isdir(audio_file):
|
||||||
|
raise ValueError(f"Audiofile {audio_file} is a directory.")
|
||||||
|
|
||||||
|
for file in gen:
|
||||||
|
print(f'shredding {file} now\n')
|
||||||
|
|
||||||
|
run(cmd , check=True)
|
||||||
|
|
||||||
|
else:
|
||||||
|
os.remove(audio_file)
|
||||||
|
print(f"Audiofile {audio_file} removed.")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_audio_file(audio_file : Union[str, torch.Tensor, ndarray],
|
||||||
|
*args, **kwargs) -> AudioProcessor:
|
||||||
|
"""Gets an audio file as TorchAudioProcessor.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_file (Union[str, torch.Tensor, ndarray]): Path to the audio file or
|
||||||
|
a tensor representing the audio.
|
||||||
|
*args: Additional positional arguments.
|
||||||
|
**kwargs: Additional keyword arguments.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
AudioProcessor: An object containing the waveform and sample rate in
|
||||||
|
torch.Tensor format.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if isinstance(audio_file, str):
|
||||||
|
audio_file = AudioProcessor.from_file(audio_file)
|
||||||
|
|
||||||
|
elif isinstance(audio_file, torch.Tensor):
|
||||||
|
audio_file = AudioProcessor(audio_file[0], audio_file[1])
|
||||||
|
elif isinstance(audio_file, ndarray):
|
||||||
|
audio_file = AudioProcessor(torch.Tensor(audio_file[0]),
|
||||||
|
audio_file[1])
|
||||||
|
|
||||||
|
if not isinstance(audio_file, AudioProcessor):
|
||||||
|
raise ValueError(f'Audiofile must be of type AudioProcessor,' \
|
||||||
|
f'not {type(audio_file)}')
|
||||||
|
return audio_file
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"Scraibe(transcriber={self.transcriber}, diariser={self.diariser})"
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"""
|
||||||
|
Command-Line Interface (CLI) for the Scraibe class,
|
||||||
|
allowing for user interaction to transcribe and diarize audio files.
|
||||||
|
The function includes arguments for specifying the audio files, model paths,
|
||||||
|
output formats, and other options necessary for transcription.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
|
||||||
|
import json
|
||||||
|
|
||||||
|
from .autotranscript import Scraibe
|
||||||
|
from .app.gradio_app import gradio_Interface
|
||||||
|
|
||||||
|
from whisper.tokenizer import LANGUAGES , TO_LANGUAGE_CODE
|
||||||
|
from torch.cuda import is_available
|
||||||
|
from torch import set_num_threads
|
||||||
|
|
||||||
|
|
||||||
|
def cli():
|
||||||
|
"""
|
||||||
|
Command-Line Interface (CLI) for the Scraibe class, allowing for user interaction to transcribe
|
||||||
|
and diarize audio files. The function includes arguments for specifying the audio files, model paths,
|
||||||
|
output formats, and other options necessary for transcription.
|
||||||
|
|
||||||
|
This function can be executed from the command line to perform transcription tasks, providing a
|
||||||
|
user-friendly way to access the Scraibe class functionalities.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def str2bool(string):
|
||||||
|
str2val = {"True": True, "False": False}
|
||||||
|
if string in str2val:
|
||||||
|
return str2val[string]
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Expected one of {set(str2val.keys())}, got {string}")
|
||||||
|
|
||||||
|
parser = ArgumentParser(formatter_class = ArgumentDefaultsHelpFormatter)
|
||||||
|
|
||||||
|
group = parser.add_mutually_exclusive_group()
|
||||||
|
|
||||||
|
parser.add_argument("-f","--audio-files", nargs="+", type=str, default=None,
|
||||||
|
help="List of audio files to transcribe.")
|
||||||
|
|
||||||
|
group.add_argument('--start-server', action='store_true',
|
||||||
|
help='Start the Gradio app.')
|
||||||
|
|
||||||
|
parser.add_argument("--port", type=int, default= None,
|
||||||
|
help="Port to run the Gradio app on. Defaults to 7860.")
|
||||||
|
|
||||||
|
parser.add_argument("--server-name", type=str, default= None,
|
||||||
|
help="Name of the Gradio app. If empty 127.0.0.1 or 0.0.0.0 will be used.")
|
||||||
|
|
||||||
|
parser.add_argument("--whisper-model-name", default="medium",
|
||||||
|
help="Name of the Whisper model to use.")
|
||||||
|
|
||||||
|
parser.add_argument("--whisper-model-directory", type=str, default= None,
|
||||||
|
help="Path to save Whisper model files; defaults to ./models/whisper.")
|
||||||
|
|
||||||
|
parser.add_argument("--diarization-directory", type=str, default= None,
|
||||||
|
help="Path to the diarization model directory.")
|
||||||
|
|
||||||
|
parser.add_argument("--hf-token", default= None, type=str,
|
||||||
|
help="HuggingFace token for private model download.")
|
||||||
|
|
||||||
|
parser.add_argument("--inference-device",
|
||||||
|
default="cuda" if is_available() else "cpu",
|
||||||
|
help="Device to use for PyTorch inference.")
|
||||||
|
|
||||||
|
parser.add_argument("--num-threads", type=int, default=0,
|
||||||
|
help="Number of threads used by torch for CPU inference; overrides MKL_NUM_THREADS/OMP_NUM_THREADS.")
|
||||||
|
|
||||||
|
parser.add_argument("--output-directory", "-o", type=str, default=".",
|
||||||
|
help="Directory to save the transcription outputs.")
|
||||||
|
|
||||||
|
parser.add_argument("--output-format", "-of", type=str, default="txt",
|
||||||
|
choices=["txt", "json", "md", "html"],
|
||||||
|
help="Format of the output file; defaults to txt.")
|
||||||
|
|
||||||
|
parser.add_argument("--verbose-output", type=str2bool, default=True,
|
||||||
|
help="Enable or disable progress and debug messages.")
|
||||||
|
|
||||||
|
parser.add_argument("--task", type=str, default= 'autotranscribe', # unifinished code
|
||||||
|
choices=["autotranscribe", "diarization",
|
||||||
|
"autotranscribe+translate", "translate", 'transcribe'],
|
||||||
|
help="Choose to perform transcription, diarization, or translation. \
|
||||||
|
If set to translate, the output will be translated to English.")
|
||||||
|
|
||||||
|
parser.add_argument("--language", type=str, default=None,
|
||||||
|
choices=sorted(LANGUAGES.keys()) + sorted([k.title() for k in TO_LANGUAGE_CODE.keys()]),
|
||||||
|
help="Language spoken in the audio. Specify None to perform language detection.")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
arg_dict = vars(args)
|
||||||
|
|
||||||
|
# configure output
|
||||||
|
out_folder = arg_dict.pop("output_directory")
|
||||||
|
os.makedirs(out_folder, exist_ok=True)
|
||||||
|
|
||||||
|
out_format = arg_dict.pop("output_format")
|
||||||
|
|
||||||
|
# seup server arg:
|
||||||
|
start_server = arg_dict.pop("start_server")
|
||||||
|
|
||||||
|
task = arg_dict.pop("task")
|
||||||
|
|
||||||
|
if args.num_threads > 0:
|
||||||
|
set_num_threads(arg_dict.pop("num_threads"))
|
||||||
|
|
||||||
|
class_kwargs = {'whisper_model' : arg_dict.pop("whisper_model_name"),
|
||||||
|
'dia_model': arg_dict.pop("diarization_directory"),
|
||||||
|
'use_auth_token' : arg_dict.pop("hf_token")}
|
||||||
|
|
||||||
|
if arg_dict["whisper_model_directory"]:
|
||||||
|
class_kwargs["download_root"] = arg_dict.pop("whisper_model_directory")
|
||||||
|
|
||||||
|
model = Scraibe(**class_kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
if arg_dict["audio_files"]:
|
||||||
|
audio_files = arg_dict.pop("audio_files")
|
||||||
|
|
||||||
|
if task == "autotranscribe" or task == "autotranscribe+translate":
|
||||||
|
for audio in audio_files:
|
||||||
|
if task == "autotranscribe+translate":
|
||||||
|
task = "translate"
|
||||||
|
else:
|
||||||
|
task = "transcribe"
|
||||||
|
|
||||||
|
out = model.autotranscribe(audio,task = task, language=arg_dict.pop("language"), verbose = arg_dict.pop("verbose_output"))
|
||||||
|
basename = audio.split("/")[-1].split(".")[0]
|
||||||
|
print(f'Saving {basename}.{out_format} to {out_folder}')
|
||||||
|
out.save(os.path.join(out_folder, f"{basename}.{out_format}"))
|
||||||
|
|
||||||
|
elif task == "diarization":
|
||||||
|
for audio in audio_files:
|
||||||
|
if arg_dict.pop("verbose_output"):
|
||||||
|
print(f"Verbose not implemented for diarization.")
|
||||||
|
|
||||||
|
out = model.diarization(audio)
|
||||||
|
basename = audio.split("/")[-1].split(".")[0]
|
||||||
|
path = os.path.join(out_folder, f"{basename}.{out_format}")
|
||||||
|
|
||||||
|
print(f'Saving {basename}.{out_format} to {out_folder}')
|
||||||
|
|
||||||
|
with open(path, "w") as f:
|
||||||
|
json.dump(json.dumps(out, indent= 1), f)
|
||||||
|
|
||||||
|
elif task == "transcribe" or task == "translate":
|
||||||
|
|
||||||
|
for audio in audio_files:
|
||||||
|
|
||||||
|
out = model.transcribe(audio, task = task,
|
||||||
|
language= arg_dict.pop("language"),
|
||||||
|
verbose = arg_dict.pop("verbose_output"))
|
||||||
|
basename = audio.split("/")[-1].split(".")[0]
|
||||||
|
path = os.path.join(out_folder, f"{basename}.{out_format}")
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write(out)
|
||||||
|
|
||||||
|
|
||||||
|
if start_server: # unfinished code
|
||||||
|
|
||||||
|
gradio_Interface(model).queue().launch(server_port=args.port, server_name=args.server_name)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
cli()
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""
|
||||||
|
Diarisation Class
|
||||||
|
------------------
|
||||||
|
|
||||||
|
This class serves as the heart of the speaker diarization system, responsible for identifying
|
||||||
|
and segmenting individual speakers from a given audio file. It leverages a pretrained model
|
||||||
|
from pyannote.audio, providing an accessible interface for audio processing tasks such as
|
||||||
|
speaker separation, and timestamping.
|
||||||
|
|
||||||
|
By encapsulating the complexities of the underlying model, it allows for straightforward
|
||||||
|
integration into various applications, ranging from transcription services to voice assistants.
|
||||||
|
|
||||||
|
Available Classes:
|
||||||
|
- Diariser: Main class for performing speaker diarization.
|
||||||
|
Includes methods for loading models, processing audio files,
|
||||||
|
and formatting the diarization output.
|
||||||
|
|
||||||
|
Constants:
|
||||||
|
- TOKEN_PATH (str): Path to the Pyannote token.
|
||||||
|
- PYANNOTE_DEFAULT_PATH (str): Default path to Pyannote models.
|
||||||
|
- PYANNOTE_DEFAULT_CONFIG (str): Default configuration for Pyannote models.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from .diarisation import Diariser
|
||||||
|
|
||||||
|
model = Diariser.load_model(model="path/to/model/config.yaml")
|
||||||
|
diarisation_output = model.diarization("path/to/audiofile.wav")
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TypeVar, Union
|
||||||
|
|
||||||
|
from pyannote.audio import Pipeline
|
||||||
|
from pyannote.audio.pipelines.speaker_diarization import SpeakerDiarization
|
||||||
|
from torch import Tensor
|
||||||
|
|
||||||
|
from .misc import PYANNOTE_DEFAULT_PATH, PYANNOTE_DEFAULT_CONFIG
|
||||||
|
Annotation = TypeVar('Annotation')
|
||||||
|
|
||||||
|
TOKEN_PATH = os.path.join(os.path.dirname(
|
||||||
|
os.path.realpath(__file__)), '.pyannotetoken')
|
||||||
|
|
||||||
|
class Diariser:
|
||||||
|
"""
|
||||||
|
Handles the diarization process of an audio file using a pretrained model
|
||||||
|
from pyannote.audio. Diarization is the task of determining "who spoke when."
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model: The pretrained model to use for diarization.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, model) -> None:
|
||||||
|
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
def diarization(self, audiofile : Union[str, Tensor, dict] ,
|
||||||
|
*args, **kwargs) -> Annotation:
|
||||||
|
"""
|
||||||
|
Perform speaker diarization on the provided audio file,
|
||||||
|
effectively separating different speakers
|
||||||
|
and providing a timestamp for each segment.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audiofile: The path to the audio file or a torch.Tensor
|
||||||
|
containing the audio data.
|
||||||
|
args: Additional arguments for the diarization model.
|
||||||
|
kwargs: Additional keyword arguments for the diarization model.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: A dictionary containing speaker names,
|
||||||
|
segments, and other information related
|
||||||
|
to the diarization process.
|
||||||
|
"""
|
||||||
|
kwargs = self._get_diarisation_kwargs(**kwargs)
|
||||||
|
|
||||||
|
diarization = self.model(audiofile,*args, **kwargs)
|
||||||
|
|
||||||
|
out = self.format_diarization_output(diarization)
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def format_diarization_output(dia : Annotation) -> dict:
|
||||||
|
"""
|
||||||
|
Formats the raw diarization output into a more usable structure for this project.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
dia: Raw diarization output.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: A structured representation of the diarization, with speaker names
|
||||||
|
as keys and a list of tuples representing segments as values.
|
||||||
|
"""
|
||||||
|
|
||||||
|
dia_list = list(dia.itertracks(yield_label=True))
|
||||||
|
diarization_output = {"speakers": [], "segments": []}
|
||||||
|
|
||||||
|
normalized_output = []
|
||||||
|
index_start_speaker = 0
|
||||||
|
index_end_speaker = 0
|
||||||
|
current_speaker = str()
|
||||||
|
|
||||||
|
###
|
||||||
|
# Sometimes two consecutive speakers are the same
|
||||||
|
# This loop removes these duplicates
|
||||||
|
###
|
||||||
|
|
||||||
|
if len(dia_list) == 1:
|
||||||
|
normalized_output.append([0, 0, dia_list[0][2]])
|
||||||
|
else:
|
||||||
|
|
||||||
|
for i, (_, _, speaker) in enumerate(dia_list):
|
||||||
|
|
||||||
|
if i == 0:
|
||||||
|
current_speaker = speaker
|
||||||
|
|
||||||
|
if speaker != current_speaker:
|
||||||
|
|
||||||
|
index_end_speaker = i - 1
|
||||||
|
|
||||||
|
normalized_output.append([index_start_speaker,
|
||||||
|
index_end_speaker,
|
||||||
|
current_speaker])
|
||||||
|
|
||||||
|
index_start_speaker = i
|
||||||
|
current_speaker = speaker
|
||||||
|
|
||||||
|
|
||||||
|
if i == len(dia_list) - 1:
|
||||||
|
|
||||||
|
index_end_speaker = i
|
||||||
|
|
||||||
|
normalized_output.append([index_start_speaker,
|
||||||
|
index_end_speaker,
|
||||||
|
current_speaker])
|
||||||
|
|
||||||
|
for outp in normalized_output:
|
||||||
|
start = dia_list[outp[0]][0].start
|
||||||
|
end = dia_list[outp[1]][0].end
|
||||||
|
|
||||||
|
diarization_output["segments"].append([start, end])
|
||||||
|
diarization_output["speakers"].append(outp[2])
|
||||||
|
return diarization_output
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _get_token():
|
||||||
|
"""
|
||||||
|
Retrieves the Huggingface token from a local file. This token is required
|
||||||
|
for accessing certain online resources.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If the token is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The Huggingface token.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if os.path.exists(TOKEN_PATH):
|
||||||
|
with open(TOKEN_PATH, 'r', encoding="utf-8") as file:
|
||||||
|
token = file.read()
|
||||||
|
else:
|
||||||
|
raise ValueError('No token found.' \
|
||||||
|
'Please create a token at https://huggingface.co/settings/token' \
|
||||||
|
f'and save it in a file called {TOKEN_PATH}')
|
||||||
|
return token
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _save_token(token):
|
||||||
|
"""
|
||||||
|
Saves the provided Huggingface token to a local file. This facilitates future
|
||||||
|
access to online resources without needing to repeatedly authenticate.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
token: The Huggingface token to save.
|
||||||
|
"""
|
||||||
|
with open(TOKEN_PATH, 'w', encoding="utf-8") as file:
|
||||||
|
file.write(token)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_model(cls,
|
||||||
|
model: str = PYANNOTE_DEFAULT_CONFIG,
|
||||||
|
use_auth_token: str = None,
|
||||||
|
cache_token: bool = True,
|
||||||
|
cache_dir: Union[Path, str] = PYANNOTE_DEFAULT_PATH,
|
||||||
|
hparams_file: Union[str, Path] = None,
|
||||||
|
*args, **kwargs
|
||||||
|
) -> Pipeline:
|
||||||
|
|
||||||
|
"""
|
||||||
|
Loads a pretrained model from pyannote.audio,
|
||||||
|
either from a local cache or online repository.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model: Path or identifier for the pyannote model.
|
||||||
|
default: /models/pyannote/speaker_diarization/config.yaml
|
||||||
|
token: Optional HUGGINGFACE_TOKEN for authenticated access.
|
||||||
|
cache_token: Whether to cache the token locally for future use.
|
||||||
|
cache_dir: Directory for caching models.
|
||||||
|
hparams_file: Path to a YAML file containing hyperparameters.
|
||||||
|
args: Additional arguments only to avoid errors.
|
||||||
|
kwargs: Additional keyword arguments only to avoid errors.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Pipeline: A pyannote.audio Pipeline object, encapsulating the loaded model.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if cache_token and use_auth_token is not None:
|
||||||
|
cls._save_token(use_auth_token)
|
||||||
|
|
||||||
|
if not os.path.exists(model) and use_auth_token is None:
|
||||||
|
use_auth_token = cls._get_token()
|
||||||
|
model = 'pyannote/speaker-diarization'
|
||||||
|
elif not os.path.exists(model) and use_auth_token is not None:
|
||||||
|
model = 'pyannote/speaker-diarization'
|
||||||
|
|
||||||
|
_model = Pipeline.from_pretrained(model,
|
||||||
|
use_auth_token = use_auth_token,
|
||||||
|
cache_dir = cache_dir,
|
||||||
|
hparams_file = hparams_file,)
|
||||||
|
|
||||||
|
if _model is None:
|
||||||
|
raise ValueError('Unable to load model either from local cache' \
|
||||||
|
'or from huggingface.co models. Please check your token' \
|
||||||
|
'or your local model path')
|
||||||
|
|
||||||
|
return cls(_model)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _get_diarisation_kwargs(**kwargs) -> dict:
|
||||||
|
"""
|
||||||
|
Validates and extracts the keyword arguments for the pyannote diarization model.
|
||||||
|
|
||||||
|
Ensures that the provided keyword arguments match the expected parameters,
|
||||||
|
filtering out any invalid or unnecessary arguments.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: A dictionary containing the validated keyword arguments.
|
||||||
|
"""
|
||||||
|
_possible_kwargs = SpeakerDiarization.apply.__code__.co_varnames
|
||||||
|
|
||||||
|
diarisation_kwargs = {k: v for k, v in kwargs.items() if k in _possible_kwargs}
|
||||||
|
|
||||||
|
return diarisation_kwargs
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"Diarisation(model={self.model})"
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
from pyannote.audio.core.model import CACHE_DIR as PYANNOTE_CACHE_DIR
|
||||||
|
|
||||||
|
CACHE_DIR = os.getenv(
|
||||||
|
"AUTOT_CACHE",
|
||||||
|
os.path.expanduser("~/.cache/torch/models"),
|
||||||
|
)
|
||||||
|
|
||||||
|
if CACHE_DIR != PYANNOTE_CACHE_DIR:
|
||||||
|
os.environ["PYANNOTE_CACHE"] = os.path.join(CACHE_DIR, "pyannote")
|
||||||
|
|
||||||
|
WHISPER_DEFAULT_PATH = os.path.join(CACHE_DIR, "whisper")
|
||||||
|
PYANNOTE_DEFAULT_PATH = os.path.join(CACHE_DIR, "pyannote")
|
||||||
|
PYANNOTE_DEFAULT_CONFIG = os.path.join(PYANNOTE_DEFAULT_PATH, "config.yaml")
|
||||||
|
|
||||||
|
def config_diarization_yaml(file_path: str, path_to_segmentation: str = None) -> None:
|
||||||
|
"""Configure diarization pipeline from a YAML file.
|
||||||
|
|
||||||
|
This function updates the YAML file to use the given segmentation model
|
||||||
|
offline, and avoids manual file manipulation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
file_path (str): Path to the YAML file.
|
||||||
|
path_to_segmentation (str, optional): Optional path to the segmentation model.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFoundError: If the segmentation model file is not found.
|
||||||
|
"""
|
||||||
|
with open(file_path, "r") as stream:
|
||||||
|
yml = yaml.safe_load(stream)
|
||||||
|
|
||||||
|
segmentation_path = path_to_segmentation or os.path.join(PYANNOTE_DEFAULT_PATH, "pytorch_model.bin")
|
||||||
|
yml["pipeline"]["params"]["segmentation"] = segmentation_path
|
||||||
|
|
||||||
|
if not os.path.exists(segmentation_path):
|
||||||
|
raise FileNotFoundError(f"Segmentation model not found at {segmentation_path}")
|
||||||
|
|
||||||
|
with open(file_path, "w") as stream:
|
||||||
|
yaml.dump(yml, stream)
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
"""
|
||||||
|
Transcriber Module
|
||||||
|
------------------
|
||||||
|
|
||||||
|
This module provides the Transcriber class, a comprehensive tool for working with Whisper models.
|
||||||
|
The Transcriber class offers functionalities such as loading different Whisper models, transcribing audio files,
|
||||||
|
and saving transcriptions to text files. It acts as an interface between various Whisper models and the user,
|
||||||
|
simplifying the process of audio transcription.
|
||||||
|
|
||||||
|
Main Features:
|
||||||
|
- Loading different sizes and versions of Whisper models.
|
||||||
|
- Transcribing audio in various formats including str, Tensor, and nparray.
|
||||||
|
- Saving the transcriptions to the specified paths.
|
||||||
|
- Adaptable to various language specifications.
|
||||||
|
- Options to control the verbosity of the transcription process.
|
||||||
|
|
||||||
|
Constants:
|
||||||
|
WHISPER_DEFAULT_PATH: Default path for downloading and loading Whisper models.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
>>> from your_package import Transcriber
|
||||||
|
>>> transcriber = Transcriber.load_model(model="medium")
|
||||||
|
>>> transcript = transcriber.transcribe(audio="path/to/audio.wav")
|
||||||
|
>>> transcriber.save_transcript(transcript, "path/to/save.txt")
|
||||||
|
"""
|
||||||
|
|
||||||
|
from whisper import Whisper, load_model
|
||||||
|
from typing import TypeVar , Union , Optional
|
||||||
|
from torch import Tensor, device
|
||||||
|
from numpy import ndarray
|
||||||
|
|
||||||
|
|
||||||
|
from .misc import WHISPER_DEFAULT_PATH
|
||||||
|
whisper = TypeVar('whisper')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class Transcriber:
|
||||||
|
"""
|
||||||
|
Transcriber Class
|
||||||
|
-----------------
|
||||||
|
|
||||||
|
The Transcriber class serves as a wrapper around Whisper models for efficient audio
|
||||||
|
transcription. By encapsulating the intricacies of loading models, processing audio,
|
||||||
|
and saving transcripts, it offers an easy-to-use interface
|
||||||
|
for users to transcribe audio files.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
model (whisper): The Whisper model used for transcription.
|
||||||
|
|
||||||
|
Methods:
|
||||||
|
transcribe: Transcribes the given audio file.
|
||||||
|
save_transcript: Saves the transcript to a file.
|
||||||
|
load_model: Loads a specific Whisper model.
|
||||||
|
_get_whisper_kwargs: Private method to get valid keyword arguments for the whisper model.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> transcriber = Transcriber.load_model(model="medium")
|
||||||
|
>>> transcript = transcriber.transcribe(audio="path/to/audio.wav")
|
||||||
|
>>> transcriber.save_transcript(transcript, "path/to/save.txt")
|
||||||
|
|
||||||
|
Note:
|
||||||
|
The class supports various sizes and versions of Whisper models. Please refer to
|
||||||
|
the load_model method for available options.
|
||||||
|
"""
|
||||||
|
def __init__(self, model: whisper ) -> None:
|
||||||
|
"""
|
||||||
|
Initialize the Transcriber class with a Whisper model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model (whisper): The Whisper model to use for transcription.
|
||||||
|
"""
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
def transcribe(self, audio : Union[str, Tensor, ndarray] ,
|
||||||
|
*args, **kwargs) -> str:
|
||||||
|
"""
|
||||||
|
Transcribe an audio file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio (Union[str, Tensor, nparray]): The audio file to transcribe.
|
||||||
|
*args: Additional arguments.
|
||||||
|
**kwargs: Additional keyword arguments,
|
||||||
|
such as the language of the audio file.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The transcript as a string.
|
||||||
|
"""
|
||||||
|
|
||||||
|
kwargs = self._get_whisper_kwargs(**kwargs)
|
||||||
|
|
||||||
|
if not kwargs.get("verbose"):
|
||||||
|
kwargs["verbose"] = None
|
||||||
|
|
||||||
|
result = self.model.transcribe(audio, *args, **kwargs)
|
||||||
|
return result["text"]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def save_transcript(transcript : str , save_path : str) -> None:
|
||||||
|
"""
|
||||||
|
Save a transcript to a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
transcript (str): The transcript as a string.
|
||||||
|
save_path (str): The path to save the transcript.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
"""
|
||||||
|
|
||||||
|
with open(save_path, 'w') as f:
|
||||||
|
f.write(transcript)
|
||||||
|
|
||||||
|
print(f'Transcript saved to {save_path}')
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_model(cls,
|
||||||
|
model: str = "medium",
|
||||||
|
download_root: str = WHISPER_DEFAULT_PATH,
|
||||||
|
device: Optional[Union[str, device]] = None,
|
||||||
|
in_memory: bool = False,
|
||||||
|
*args, **kwargs
|
||||||
|
) -> 'Transcriber':
|
||||||
|
"""
|
||||||
|
Load whisper model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model (str): Whisper model. Available models include:
|
||||||
|
- 'tiny.en'
|
||||||
|
- 'tiny'
|
||||||
|
- 'base.en'
|
||||||
|
- 'base'
|
||||||
|
- 'small.en'
|
||||||
|
- 'small'
|
||||||
|
- 'medium.en'
|
||||||
|
- 'medium'
|
||||||
|
- 'large-v1'
|
||||||
|
- 'large-v2'
|
||||||
|
- 'large'
|
||||||
|
|
||||||
|
download_root (str, optional): Path to download the model.
|
||||||
|
Defaults to WHISPER_DEFAULT_PATH.
|
||||||
|
|
||||||
|
device (Optional[Union[str, torch.device]], optional):
|
||||||
|
Device to load model on. Defaults to None.
|
||||||
|
in_memory (bool, optional): Whether to load model in memory.
|
||||||
|
Defaults to False.
|
||||||
|
args: Additional arguments only to avoid errors.
|
||||||
|
kwargs: Additional keyword arguments only to avoid errors.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Transcriber: A Transcriber object initialized with the specified model.
|
||||||
|
"""
|
||||||
|
|
||||||
|
_model = load_model(model, download_root=download_root,
|
||||||
|
device=device, in_memory=in_memory)
|
||||||
|
|
||||||
|
return cls(_model)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _get_whisper_kwargs(**kwargs) -> dict:
|
||||||
|
"""
|
||||||
|
Get kwargs for whisper model. Ensure that kwargs are valid.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Keyword arguments for whisper model.
|
||||||
|
"""
|
||||||
|
_possible_kwargs = Whisper.transcribe.__code__.co_varnames
|
||||||
|
|
||||||
|
whisper_kwargs = {k: v for k, v in kwargs.items() if k in _possible_kwargs}
|
||||||
|
|
||||||
|
if (task := kwargs.get("task")):
|
||||||
|
whisper_kwargs["task"] = task
|
||||||
|
|
||||||
|
if (language := kwargs.get("language")):
|
||||||
|
whisper_kwargs["language"] = language
|
||||||
|
|
||||||
|
return whisper_kwargs
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"Transcriber(model={self.model})"
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
import json
|
||||||
|
import time
|
||||||
|
from traceback import print_stack
|
||||||
|
|
||||||
|
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
ALPHABET = [*"abcdefghijklmnopqrstuvwxyz"]
|
||||||
|
|
||||||
|
|
||||||
|
class Transcript:
|
||||||
|
"""
|
||||||
|
Class for storing transcript data, including speaker information and text segments,
|
||||||
|
and exporting it to various file formats such as JSON, HTML, and LaTeX.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, transcript: dict) -> None:
|
||||||
|
"""
|
||||||
|
Initializes the Transcript object with the given transcript data.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
transcript (dict): A dictionary containing the formatted transcript string.
|
||||||
|
Keys should correspond to segment IDs, and values should
|
||||||
|
contain speaker and segment information.
|
||||||
|
"""
|
||||||
|
|
||||||
|
self.transcript = transcript
|
||||||
|
self.speakers = self._extract_speakers()
|
||||||
|
self.segments = self._extract_segments()
|
||||||
|
self.annotation = {}
|
||||||
|
|
||||||
|
def annotate(self, *args, **kwargs) -> dict:
|
||||||
|
"""
|
||||||
|
Annotates the transcript to associate specific names with speakers.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
args (list): List of speaker names. These will be mapped sequentially to the speakers.
|
||||||
|
kwargs (dict): Dictionary with speaker names as keys and list of segments as values.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Dictionary with speaker names as keys and list of segments as values.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If the number of speaker names does not match the number
|
||||||
|
of speakers, or if an unknown speaker is found.
|
||||||
|
"""
|
||||||
|
|
||||||
|
annotations = {}
|
||||||
|
if args and len(args) != len(self.speakers):
|
||||||
|
raise ValueError("Number of speaker names does not match number of speakers")
|
||||||
|
|
||||||
|
if args:
|
||||||
|
for arg, speaker in zip(args, sorted(self.speakers)):
|
||||||
|
|
||||||
|
annotations[speaker] = arg
|
||||||
|
|
||||||
|
invalid_speakers = set(kwargs.keys()) - set(self.speakers)
|
||||||
|
if invalid_speakers:
|
||||||
|
raise ValueError(f"These keys are not speakers: {', '.join(invalid_speakers)}")
|
||||||
|
|
||||||
|
annotations.update({key: kwargs[key] for key in self.speakers if key in kwargs})
|
||||||
|
|
||||||
|
self.annotation = annotations
|
||||||
|
|
||||||
|
return self
|
||||||
|
|
||||||
|
def _extract_speakers(self) -> list:
|
||||||
|
"""
|
||||||
|
Extracts the unique speaker names from the transcript.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list: List of unique speaker names in the transcript.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return list(set([self.transcript[id]["speakers"] for id in self.transcript]))
|
||||||
|
|
||||||
|
def _extract_segments(self) -> list:
|
||||||
|
"""
|
||||||
|
Extracts all the text segments from the transcript.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list: List of segments, where each segment is represented
|
||||||
|
by the starting and ending times.
|
||||||
|
"""
|
||||||
|
return [self.transcript[id]["segments"] for id in self.transcript]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
"""
|
||||||
|
Converts the transcript to a string representation.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: String representation of the transcript, including speaker names and
|
||||||
|
time stamps for each segment.
|
||||||
|
"""
|
||||||
|
fstring = ""
|
||||||
|
|
||||||
|
for _id in self.transcript:
|
||||||
|
seq = self.transcript[_id]
|
||||||
|
|
||||||
|
if self.annotation:
|
||||||
|
speaker = self.annotation[seq["speakers"]]
|
||||||
|
else:
|
||||||
|
speaker = seq["speakers"]
|
||||||
|
|
||||||
|
segm = seq["segments"]
|
||||||
|
sseg = time.strftime("%H:%M:%S",time.gmtime(segm[0]))
|
||||||
|
eseg = time.strftime("%H:%M:%S",time.gmtime(segm[1]))
|
||||||
|
|
||||||
|
fstring += f"{speaker} ({sseg} ; {eseg}):\t{seq['text']}\n"
|
||||||
|
|
||||||
|
return fstring
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
"""Return a string representation of the Transcript object.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: A string that provides an informative description of the object.
|
||||||
|
"""
|
||||||
|
return f"Transcript(speakers = {self.speakers},"\
|
||||||
|
f"segments = {self.segments}, annotation = {self.annotation})"
|
||||||
|
|
||||||
|
def get_dict(self) -> dict:
|
||||||
|
"""
|
||||||
|
Get transcript as dict
|
||||||
|
|
||||||
|
:return: transcript as dict
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
|
||||||
|
return self.transcript
|
||||||
|
|
||||||
|
def get_json(self, *args, use_annotation : bool = True, **kwargs) -> str:
|
||||||
|
"""
|
||||||
|
Get transcript as json string
|
||||||
|
:return: transcript as json string
|
||||||
|
:rtype: str
|
||||||
|
"""
|
||||||
|
if "indent" not in kwargs:
|
||||||
|
kwargs["indent"] = 3
|
||||||
|
|
||||||
|
if use_annotation and self.annotation:
|
||||||
|
for _id in self.transcript:
|
||||||
|
seq = self.transcript[_id]
|
||||||
|
seq["speakers"] = self.annotation[seq["speakers"]]
|
||||||
|
|
||||||
|
return json.dumps(self.transcript, *args, **kwargs)
|
||||||
|
|
||||||
|
def get_html(self) -> str:
|
||||||
|
"""
|
||||||
|
Get transcript as html string
|
||||||
|
|
||||||
|
:return: transcript as html string
|
||||||
|
:rtype: str
|
||||||
|
"""
|
||||||
|
html = "<p>" + self.__str__().replace("\n", "<br>") + "</p>"
|
||||||
|
html = "<html><body>" + html + "</body></html>"
|
||||||
|
html = html.replace("\t", " ")
|
||||||
|
|
||||||
|
return html
|
||||||
|
|
||||||
|
def get_md(self) -> str:
|
||||||
|
"""Get transcript as Markdown string, using HTML formatting.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Transcript as a Markdown string.
|
||||||
|
"""
|
||||||
|
return self.get_html()
|
||||||
|
|
||||||
|
def get_tex(self) -> str:
|
||||||
|
"""Get transcript as LaTeX string. If no annotations are present, the speakers will
|
||||||
|
be annotated with the first letters of the alphabet.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Transcript as LaTeX string.
|
||||||
|
"""
|
||||||
|
if not self.annotation:
|
||||||
|
|
||||||
|
self.annotate(*ALPHABET[:len(self.speakers)])
|
||||||
|
|
||||||
|
fstring ="\\begin{drama}"
|
||||||
|
|
||||||
|
for speaker in self.speakers:
|
||||||
|
|
||||||
|
fstring += "\n\t\\Character{"+ str(self.annotation[speaker]) + "}" \
|
||||||
|
"{"+ str(self.annotation[speaker]) + "}"
|
||||||
|
|
||||||
|
for id in self.transcript:
|
||||||
|
seq = self.transcript[id]
|
||||||
|
speaker = self.annotation[seq["speakers"]]
|
||||||
|
fstring += f"\n\\{speaker}speaks:\n{seq['text']}"
|
||||||
|
|
||||||
|
fstring += "\n\\end{drama}"
|
||||||
|
|
||||||
|
return fstring
|
||||||
|
|
||||||
|
|
||||||
|
def to_json(self,path, *args, **kwargs) -> None:
|
||||||
|
"""Save transcript as json file
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): path to save file
|
||||||
|
"""
|
||||||
|
with open(path, "w") as f:
|
||||||
|
json.dump(self.transcript, f, *args, **kwargs)
|
||||||
|
|
||||||
|
def to_txt(self, path: str) -> None:
|
||||||
|
"""Save transcript as a LaTeX file (placeholder function, implementation needed).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): Path to save the LaTeX file.
|
||||||
|
"""
|
||||||
|
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write(self.__str__())
|
||||||
|
|
||||||
|
def to_md(self, path: str) -> None:
|
||||||
|
"""Get transcript as Markdown string, using HTML formatting.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: Transcript as a Markdown string.
|
||||||
|
"""
|
||||||
|
return self.to_html(path)
|
||||||
|
|
||||||
|
def to_html(self, path: str) -> None:
|
||||||
|
"""
|
||||||
|
Save transcript as html file
|
||||||
|
|
||||||
|
:param path: path to save file
|
||||||
|
:type path: str
|
||||||
|
"""
|
||||||
|
|
||||||
|
with open(path, "w") as file:
|
||||||
|
file.write(self.get_html())
|
||||||
|
|
||||||
|
def to_tex(self, path: str) -> None:
|
||||||
|
"""Save transcript as a LaTeX file (placeholder function, implementation needed).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): Path to save the LaTeX file.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def to_pdf(self, path: str) -> None:
|
||||||
|
"""Save transcript as a PDF file (placeholder function, implementation needed).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): Path to save the PDF file.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def save(self, path: str, *args, **kwargs) -> None:
|
||||||
|
"""Save transcript to file with the given path and file format.
|
||||||
|
|
||||||
|
This method can save the transcript in various formats including JSON, TXT,
|
||||||
|
MD, HTML, TEX, and PDF. The file format is determined by the extension of
|
||||||
|
the path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): Path to save the file, including the desired file extension.
|
||||||
|
*args: Additional positional arguments to be passed to the specific save methods.
|
||||||
|
**kwargs: Additional keyword arguments to be passed to the specific save methods.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If the file format specified in the path is unknown.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if path.endswith(".json"):
|
||||||
|
self.to_json(path, *args, **kwargs)
|
||||||
|
elif path.endswith(".txt"):
|
||||||
|
self.to_txt(path, *args, **kwargs)
|
||||||
|
elif path.endswith(".md"):
|
||||||
|
self.to_md(path, *args, **kwargs)
|
||||||
|
elif path.endswith(".html"):
|
||||||
|
self.to_html(path, *args, **kwargs)
|
||||||
|
elif path.endswith(".tex"):
|
||||||
|
self.to_tex(path, *args, **kwargs)
|
||||||
|
elif path.endswith(".pdf"):
|
||||||
|
self.to_pdf(path, *args, **kwargs)
|
||||||
|
else:
|
||||||
|
raise ValueError("Unknown file format")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_json(cls, json: Union[dict, str]) -> "Transcript":
|
||||||
|
"""Load transcript from json file
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path (str): path to json file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Transcript: Transcript object
|
||||||
|
"""
|
||||||
|
if isinstance(json, dict):
|
||||||
|
return cls(json)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
transcript = json.loads(json)
|
||||||
|
except:
|
||||||
|
with open(json, "r") as f:
|
||||||
|
transcript = json.load(f)
|
||||||
|
|
||||||
|
return cls(transcript)
|
||||||
|
|
||||||
|
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import os
|
import os
|
||||||
import subprocess as sp
|
import subprocess as sp
|
||||||
|
|
||||||
MAJOR = 1
|
MAJOR = 0
|
||||||
MINOR = 0
|
MINOR = 1
|
||||||
MICRO = 0
|
MICRO = 0
|
||||||
MICRO_POST = 0
|
MICRO_POST = 0
|
||||||
ISRELEASED = False
|
ISRELEASED = False
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
[metadata]
|
||||||
|
name = scraibe
|
||||||
|
version = attr: scraibe.__version__
|
||||||
|
author = Jacob Schmieder
|
||||||
|
author_email = Jacob.Schmieder@dbfz.de
|
||||||
|
description = My package description
|
||||||
|
long_description = file: README.md, LICENSE
|
||||||
|
platforms = Linux
|
||||||
|
keywords = transcription speech recognition whisper pyannote audio speech-to-text speech-to-text transcription speech-to-text recognition voice-to-speech
|
||||||
|
license = GPL-3.0
|
||||||
|
classifiers =
|
||||||
|
Development Status :: 3 - Alpha
|
||||||
|
Environment :: GPU :: NVIDIA CUDA :: 11.2
|
||||||
|
License :: OSI Approved :: Open Software License 3.0 (OSL-3.0)
|
||||||
|
Topic :: Scientific/Engineering :: Artificial Intelligence
|
||||||
|
Programming Language :: Python :: 3.8
|
||||||
|
Programming Language :: Python :: 3.9
|
||||||
|
Programming Language :: Python :: 3.10
|
||||||
|
|
||||||
|
[options]
|
||||||
|
zip_safe = False
|
||||||
|
include_package_data = True
|
||||||
|
packages = find:
|
||||||
|
python_requires = >=3.7
|
||||||
|
install_requires =
|
||||||
|
requests
|
||||||
|
importlib-metadata; python_version<"3.8"
|
||||||
|
|
||||||
|
[options.entry_points]
|
||||||
|
console_scripts =
|
||||||
|
executable-name = scraibe.cli:cli
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
|
from calendar import c
|
||||||
import pkg_resources
|
import pkg_resources
|
||||||
import os
|
import os
|
||||||
from setuptools import setup, find_packages
|
from setuptools import setup, find_packages
|
||||||
|
|
||||||
module_name = "autotranscript"
|
module_name = "scraibe"
|
||||||
github_url = "https://github.com/Jaikinator/transcriptor"
|
github_url = "https://github.com/JSchmie/autotranscript"
|
||||||
|
|
||||||
file_dir = os.path.dirname(os.path.realpath(__file__))
|
file_dir = os.path.dirname(os.path.realpath(__file__))
|
||||||
absdir = lambda p: os.path.join(file_dir, p)
|
absdir = lambda p: os.path.join(file_dir, p)
|
||||||
@@ -15,24 +16,45 @@ version = {"__file__": verfile}
|
|||||||
with open(verfile, "r") as fp:
|
with open(verfile, "r") as fp:
|
||||||
exec(fp.read(), version)
|
exec(fp.read(), version)
|
||||||
|
|
||||||
|
|
||||||
############### setup ###############
|
############### setup ###############
|
||||||
|
|
||||||
build_version = "OPTB_BUILD" in os.environ
|
build_version = "SCRAIBE_BUILD" in os.environ
|
||||||
|
|
||||||
setup(
|
if __name__ == "__main__":
|
||||||
name=module_name,
|
|
||||||
version=version["get_version"](build_version),
|
setup(
|
||||||
packages=find_packages(),
|
name=module_name,
|
||||||
python_requires="~=3.9",
|
version=version["get_version"](build_version),
|
||||||
readme="README.md",
|
packages=find_packages(),
|
||||||
install_requires = [str(r) for r in pkg_resources.parse_requirements(
|
python_requires=">=3.8",
|
||||||
open(os.path.join(os.path.dirname(__file__), "requirements.txt"))
|
readme="README.md",
|
||||||
)
|
install_requires = [str(r) for r in pkg_resources.parse_requirements(
|
||||||
],
|
open(os.path.join(os.path.dirname(__file__), "requirements.txt"))
|
||||||
url= github_url,
|
)
|
||||||
license='',
|
],
|
||||||
author='Jacob Schmieder',
|
dependency_links=[
|
||||||
author_email='',
|
'https://download.pytorch.org/whl/cu113',
|
||||||
description='Transcription tool for audio files based on Whisper',
|
],
|
||||||
#entry_points={'console_scripts': ['autotranscript = autotranscript.__main__:main']}
|
url= github_url,
|
||||||
)
|
|
||||||
|
license='GPL-3',
|
||||||
|
author='Jacob Schmieder',
|
||||||
|
author_email='Jacob.Schmieder@dbfz.de',
|
||||||
|
description='Transcription tool for audio files based on Whisper and Pyannote',
|
||||||
|
classifiers=[
|
||||||
|
'Development Status :: 3 - Alpha',
|
||||||
|
'Environment :: GPU :: NVIDIA CUDA :: 11.2',
|
||||||
|
'License :: OSI Approved :: Open Software License 3.0 (OSL-3.0)',
|
||||||
|
'Topic :: Scientific/Engineering :: Artificial Intelligence',
|
||||||
|
'Programming Language :: Python :: 3.8',
|
||||||
|
'Programming Language :: Python :: 3.9',
|
||||||
|
'Programming Language :: Python :: 3.10'],
|
||||||
|
keywords = ['transcription', 'speech recognition', 'whisper', 'pyannote', 'audio',
|
||||||
|
'speech-to-text', 'speech-to-text transcription', 'speech-to-text recognition',
|
||||||
|
'voice-to-speech'],
|
||||||
|
package_data={'scraibe.app' : ["*.html", "*.svg"]},
|
||||||
|
entry_points={'console_scripts':
|
||||||
|
['scraibe = scraibe.cli:cli']}
|
||||||
|
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import pytest
|
||||||
|
from scraibe import Transcriber
|
||||||
|
from unittest.mock import patch, mock_open
|
||||||
|
import os
|
||||||
|
|
||||||
|
def test_load_pyannote_model():
|
||||||
|
"""
|
||||||
|
Test load_pyannote_test
|
||||||
|
"""
|
||||||
|
from pyannote.audio.pipelines.speaker_diarization import SpeakerDiarization
|
||||||
|
from pyannote.audio import Pipeline
|
||||||
|
|
||||||
|
pipeline = Pipeline.from_pretrained("models/pyannote/speaker_diarization/config.yaml")
|
||||||
|
assert isinstance(pipeline, SpeakerDiarization)
|
||||||
|
|
||||||
|
# Test Transcribtion class
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def transcriber():
|
||||||
|
"""
|
||||||
|
Prepare Transcriber for testing
|
||||||
|
Returns: Transcriber Object
|
||||||
|
"""
|
||||||
|
|
||||||
|
return Transcriber.load_model("medium", local=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_Transcriber_init(transcriber):
|
||||||
|
"""
|
||||||
|
Test Transcriber initialization with a whisper model
|
||||||
|
"""
|
||||||
|
|
||||||
|
assert isinstance(transcriber, Transcriber)
|
||||||
|
|
||||||
|
def test_transcription(transcriber):
|
||||||
|
"""
|
||||||
|
Test transcription
|
||||||
|
"""
|
||||||
|
|
||||||
|
transcript = transcriber.transcribe("tests/test.wav")
|
||||||
|
assert isinstance(transcript, str)
|
||||||
|
|
||||||
|
def test_save_transcript_to_file(transcriber):
|
||||||
|
"""
|
||||||
|
Test save_transcript_to_file
|
||||||
|
"""
|
||||||
|
transcript = transcriber.transcribe("tests/test.wav")
|
||||||
|
|
||||||
|
Transcriber.save_transcript(transcript, "tests/output.txt")
|
||||||
|
|
||||||
|
assert os.path.exists("tests/output.txt")
|
||||||
|
|
||||||
|
os.remove("tests/output.txt")
|
||||||
|
|
||||||
|
# Test Diaraization class
|
||||||
|
|
||||||
|
from scraibe import Diariser
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def diarisation():
|
||||||
|
"""
|
||||||
|
Prepare Diarisation for testing
|
||||||
|
Returns: Diarisation Object
|
||||||
|
"""
|
||||||
|
|
||||||
|
return Diariser.load_model("models/pyannote/speaker_diarization/config.yaml", local=True)
|
||||||
|
|
||||||
|
def test_Diarisation_init(diarisation):
|
||||||
|
"""
|
||||||
|
Test Diarisation initialization with a pyannote model
|
||||||
|
"""
|
||||||
|
|
||||||
|
assert isinstance(diarisation, Diariser)
|
||||||
|
|
||||||
|
def test_diarisation(diarisation):
|
||||||
|
"""
|
||||||
|
Test diarisation
|
||||||
|
"""
|
||||||
|
|
||||||
|
diarisation = diarisation.diarization("tests/test.wav")
|
||||||
|
assert isinstance(diarisation, dict)
|
||||||
|
|
||||||
|
# Test AudioProcessor
|
||||||
|
|
||||||
|
from scraibe import AudioProcessor , TorchAudioProcessor
|
||||||
|
|
||||||
|
|
||||||
|
def test_AudioProcessor_init():
|
||||||
|
"""
|
||||||
|
Test AudioProcessor initialization
|
||||||
|
"""
|
||||||
|
audio = AudioProcessor("tests/test.wav")
|
||||||
|
assert isinstance(audio, AudioProcessor)
|
||||||
|
|
||||||
|
def test_AudioProcessor_convert():
|
||||||
|
"""
|
||||||
|
Test AudioProcessor convert
|
||||||
|
"""
|
||||||
|
audio = AudioProcessor("tests/test.wav")
|
||||||
|
audio.convert_audio("tests/test.mp3", format="mp3")
|
||||||
|
assert os.path.exists("tests/test.mp3")
|
||||||
|
|
||||||
|
def test_TorchAudioProcessor_from_file():
|
||||||
|
"""
|
||||||
|
Test TorchAudioProcessor initialization
|
||||||
|
"""
|
||||||
|
audio = TorchAudioProcessor.from_file("tests/test.wav")
|
||||||
|
|
||||||
|
assert isinstance(audio, TorchAudioProcessor)
|
||||||
|
|
||||||
|
os.remove("tests/test.mp3")
|
||||||
|
|
||||||
|
|
||||||
|
def test_TorchAudioProcessor_from_ffmpeg():
|
||||||
|
"""
|
||||||
|
Test TorchAudioProcessor initialization
|
||||||
|
"""
|
||||||
|
audio = TorchAudioProcessor.from_ffmpeg("tests/test.wav")
|
||||||
|
assert isinstance(audio, TorchAudioProcessor)
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
from autotranscript import AutoTranscribe
|
|
||||||
|
|
||||||
AutoTranscribe(diarisation=True).transcribe()
|
|
||||||