Initial commit
This commit is contained in:
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
whishper_data/
|
||||||
|
node_modules/
|
||||||
|
__pycache__/
|
||||||
|
whisper_models/
|
||||||
|
.venv
|
||||||
|
.vscode
|
||||||
|
*cache*
|
||||||
|
*override*
|
||||||
|
*_WHSHPR_*
|
||||||
|
.env
|
||||||
4
CHANGELOG.md
Normal file
4
CHANGELOG.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# v1.0.0 (2023-08-25)
|
||||||
|
|
||||||
|
Initial release of Whishper!
|
||||||
|
|
||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
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 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 work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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 Affero 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 Affero 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 Affero 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) 2023 pluja
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
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 AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
50
README.md
Normal file
50
README.md
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|

|
||||||
|
|
||||||
|
# [Whishper](https://whishper.net)
|
||||||
|
|
||||||
|
Whishper (formerly known as Web Whisper Plus) is a complete transcription suite. In simple words, it is a frontend for OpenAI's Whisper, but with batteries included!
|
||||||
|
|
||||||
|
> [Checkout the website for more information](https://whishper.net)
|
||||||
|
|
||||||
|
> [Demo videos available here](https://whishper.net/usage/transcriptions/)
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Transcribe any media to text: audio, video, etc.
|
||||||
|
- Transcribe from URLs (any source supported by yt-dlp).
|
||||||
|
- Upload a file to transcribe.
|
||||||
|
- Download result in many formats: TXT, JSON, VTT, SRT or copy the raw text to your clipboard.
|
||||||
|
- Translate your transcriptions to any language supported by [Libretranslate](https://libretranslate.com).
|
||||||
|
- Edit your subtitles in a comfy and complete web UI!
|
||||||
|
- Subtitle language selection.
|
||||||
|
- Sentence splitting.
|
||||||
|
- Large CPS (Characters per second) warnings.
|
||||||
|
- See current transcription based on media position.
|
||||||
|
- Insert new segments to the subtitles.
|
||||||
|
- Private: transcription, translation and subtitle edition happen 100% locally (can work offline!).
|
||||||
|
- Fast: uses FasterWhisper as the Whisper backend: get much faster transcription times on CPU!
|
||||||
|
- Local: transcripted files are stored locally, and you can download them!
|
||||||
|
|
||||||
|
### Coming soon
|
||||||
|
|
||||||
|
- [ ] Support for GPU acceleration.
|
||||||
|
- [ ] Audio recording from the browser.
|
||||||
|
|
||||||
|
## Self hosting
|
||||||
|
|
||||||
|
Check out the self-hosting documentation [here](https://whishper.net/guides/install/).
|
||||||
|
|
||||||
|
## Project structure
|
||||||
|
|
||||||
|
Whishper is a collection of pieces that work together. The three main pieces are:
|
||||||
|
|
||||||
|
- Transcription-API: This is the API that enables running Faster-Whisper. You can find it in the `transcription-api` folder.
|
||||||
|
- Whishper-Backend: This is the backend that coordinates frontend calls, database, and tasks. You can find it in `backend` folder.
|
||||||
|
- Whishper-Frontend: This is the frontend (web UI) of the application. You can find it in `frontend` folder.
|
||||||
|
- Translation (3rd party): This is the libretranslate container that is used for translating subtitles.
|
||||||
|
- MongoDB (3rd party): This is the database that stores all the information about your transcriptions.
|
||||||
|
- Nginx (3rd party): This is the proxy that allows running everything from a single domain.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
Check out the development documentation [here](https://whishper.net/guides/development/).
|
||||||
31
backend/Dockerfile
Normal file
31
backend/Dockerfile
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
FROM --platform=$BUILDPLATFORM golang:bookworm AS ytdlp_cache
|
||||||
|
ARG TARGETOS
|
||||||
|
ARG TARGETARCH
|
||||||
|
RUN apt update && apt install -y wget
|
||||||
|
RUN wget https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -O /usr/local/bin/yt-dlp
|
||||||
|
RUN chmod a+rx /usr/local/bin/yt-dlp
|
||||||
|
|
||||||
|
FROM devopsworks/golang-upx:latest as builder
|
||||||
|
ENV DEBIAN_FRONTEND noninteractive
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . .
|
||||||
|
RUN go mod tidy
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o whishper . && \
|
||||||
|
upx whishper
|
||||||
|
|
||||||
|
RUN chmod a+rx whishper
|
||||||
|
|
||||||
|
FROM --platform=$BUILDPLATFORM python:3-bookworm
|
||||||
|
ARG TARGETOS
|
||||||
|
ARG TARGETARCH
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=builder /app/whishper ./whishper
|
||||||
|
RUN chmod a+rx ./whishper
|
||||||
|
|
||||||
|
COPY --from=ytdlp_cache /usr/local/bin/yt-dlp /bin/yt-dlp
|
||||||
|
|
||||||
|
RUN mkdir /app/uploads
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
ENTRYPOINT [ "/app/whishper", "-addr", ":8080", "-dev" ]
|
||||||
66
backend/README.md
Normal file
66
backend/README.md
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
# Golang API for Whishper
|
||||||
|
|
||||||
|
This is the Golang API for Whishper. It allows to have an interface between the Faster-Whisper-ASR service, the database and the web interface.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Websocket
|
||||||
|
|
||||||
|
It exposes a `/ws/transcriptions` websocket endpoint where JSON events will be received. This endpoint only receives updates, it will not send all the transcriptions in the database to the client when it connects. The websocket will also ignore all the events from the clients.
|
||||||
|
|
||||||
|
### REST API
|
||||||
|
|
||||||
|
#### GET: `/api/transcriptions`
|
||||||
|
|
||||||
|
This endpoint will return all the transcriptions in the database.
|
||||||
|
|
||||||
|
#### POST: `/api/transcriptions`
|
||||||
|
|
||||||
|
This endpoint expects a form with the following fields:
|
||||||
|
|
||||||
|
- `file` (form file): The file to transcribe (must be present, if `sourceURL` is not present)
|
||||||
|
- `sourceURL` (string): The URL of the file to transcribe (optional, if present, `file` will be ignored)
|
||||||
|
- `modelSize` (string): The model size to use (optional, if not present, the default model size will be used). The available model sizes are: `tiny`, `base`, `small`, `medium`, `large`. All variants of the model size are also available with enlgish-only models (e.g. `tiny.en`, `base.en`, etc.)
|
||||||
|
- `language` (string): The source language for the transcription. By default it uses `auto` which will detect the language automatically. Otherwise, use a two-letter language code (e.g. `en`, `fr`, `es`, etc.)
|
||||||
|
|
||||||
|
### Flags
|
||||||
|
|
||||||
|
- `-addr`: The address to listen to (default: `:8080`). Must specify the `:` before the port number.
|
||||||
|
- `-updir`: The path to the uploads directory (default: `/app/uploads`). Must exist and be writable.
|
||||||
|
- `-asr`: The address of the ASR service (default: `whisper-api:8000`).
|
||||||
|
- `-translation`: The address of the translation service (default: `translate:5000`).
|
||||||
|
- `-dev`: Turns development mode on. This will show debug logs.
|
||||||
|
|
||||||
|
## Project structure
|
||||||
|
|
||||||
|
# `main.go`
|
||||||
|
|
||||||
|
This is the main file of the project. It contains the main function calls.
|
||||||
|
|
||||||
|
# `api/`
|
||||||
|
|
||||||
|
This folder contains all the server logic. It is split into three files:
|
||||||
|
|
||||||
|
- `server.go`: This file contains the main server logic. It creates a server struct that contains all the necessary logic to run the server.
|
||||||
|
- `handlers.go`: This file contains all the handlers for the server. It also contains the logic.
|
||||||
|
- `websocket.go`: This file contains the logic for the websocket.
|
||||||
|
|
||||||
|
# `models/`
|
||||||
|
|
||||||
|
This folder contains all the models used by the server. Each model has its own file.
|
||||||
|
|
||||||
|
# `utils/`
|
||||||
|
|
||||||
|
This folder contains all the utility functions used by the server.
|
||||||
|
|
||||||
|
# `database/`
|
||||||
|
|
||||||
|
This folder contains all the database logic. It is split into two files:
|
||||||
|
|
||||||
|
- `database.go`: This file contains the main database logic. It creates a database interface that contains all the necessary logic to interact with the database.
|
||||||
|
- `mongo.go`: This implements the database interface for MongoDB.
|
||||||
|
|
||||||
|
# `monitor/`
|
||||||
|
|
||||||
|
This folder contains the logic for the background monitor that checks the pending transcriptions, transcribes them and updates the database.
|
||||||
|
|
||||||
190
backend/api/handlers.go
Normal file
190
backend/api/handlers.go
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/goccy/go-json"
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) handleGetAllTranscriptions(c *fiber.Ctx) error {
|
||||||
|
transcriptions := s.Db.GetAllTranscriptions()
|
||||||
|
|
||||||
|
// Convert the transcriptions to JSON.
|
||||||
|
json, err := json.Marshal(transcriptions)
|
||||||
|
if err != nil {
|
||||||
|
// 503 On vacation!
|
||||||
|
return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the JSON to the response body.
|
||||||
|
c.Set("Content-Type", "application/json")
|
||||||
|
c.Write(json)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleGetTranscriptionById(c *fiber.Ctx) error {
|
||||||
|
id := c.Params("id")
|
||||||
|
t := s.Db.GetTranscription(id)
|
||||||
|
if t == nil {
|
||||||
|
log.Warn().Msgf("Transcription with id %v not found", id)
|
||||||
|
return fiber.NewError(fiber.StatusNotFound, "Not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert the transcription to JSON.
|
||||||
|
json, err := json.Marshal(t)
|
||||||
|
if err != nil {
|
||||||
|
// 503 On vacation!
|
||||||
|
return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the JSON to the response body.
|
||||||
|
c.Set("Content-Type", "application/json")
|
||||||
|
c.Write(json)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// This function receives data from a form to create a new transcription.
|
||||||
|
// If the transcription is created successfully, it returns a 201 Created status code and
|
||||||
|
// broadcasts the new transcription to all ws clients.
|
||||||
|
func (s *Server) handlePostTranscription(c *fiber.Ctx) error {
|
||||||
|
log.Debug().Msg("POST /api/transcriptions")
|
||||||
|
var transcription models.Transcription
|
||||||
|
|
||||||
|
// we get the filename from the from
|
||||||
|
var filename string
|
||||||
|
if c.FormValue("sourceUrl") == "" {
|
||||||
|
// Get the form file from the request.
|
||||||
|
file, err := c.FormFile("file")
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error getting file field from the form")
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "Bad request")
|
||||||
|
}
|
||||||
|
timeid := time.Now().Format("2006_01_02-150405000")
|
||||||
|
filename = timeid + models.FileNameSeparator + file.Filename
|
||||||
|
// if it's empty and there is no sourceurl we set a timestamp-based filename
|
||||||
|
if filename == timeid+models.FileNameSeparator {
|
||||||
|
filename = timeid + models.FileNameSeparator + time.Now().Format("2006_01_02-150405")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the file to the uploads directory.
|
||||||
|
err = c.SaveFile(file, fmt.Sprintf("%v/%v", os.Getenv("UPLOAD_DIR"), filename))
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msgf("Error saving the form file to disk into %v", os.Getenv("UPLOAD_DIR"))
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Internal server error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the body into the transcription struct.
|
||||||
|
transcription.Language = c.FormValue("language")
|
||||||
|
transcription.ModelSize = c.FormValue("modelSize")
|
||||||
|
transcription.FileName = filename
|
||||||
|
transcription.Status = models.TranscriptionStatusPending
|
||||||
|
transcription.Task = "transcribe"
|
||||||
|
transcription.SourceUrl = c.FormValue("sourceUrl")
|
||||||
|
// TODO: Implement other device types
|
||||||
|
transcription.Device = "cpu"
|
||||||
|
|
||||||
|
log.Debug().Msgf("Transcription: %+v", transcription)
|
||||||
|
// Save transcription to database
|
||||||
|
res, err := s.Db.NewTranscription(&transcription)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error saving transcription to database")
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Internal server error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the JSON to the response body.
|
||||||
|
s.BroadcastTranscription(res)
|
||||||
|
s.NewTranscriptionCh <- true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleDeleteTranscription(c *fiber.Ctx) error {
|
||||||
|
// First get the transcription from the database
|
||||||
|
id := c.Params("id")
|
||||||
|
t := s.Db.GetTranscription(id)
|
||||||
|
if t == nil {
|
||||||
|
log.Warn().Msgf("Transcription with id %v not found", id)
|
||||||
|
return fiber.NewError(fiber.StatusNotFound, "Not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then delete the file from disk
|
||||||
|
err := os.Remove(fmt.Sprintf("%v/%v", os.Getenv("UPLOAD_DIR"), t.FileName))
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msgf("Error deleting file %v", t.FileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally delete the transcription from the database
|
||||||
|
err = s.Db.DeleteTranscription(id)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msgf("Error deleting transcription %v", id)
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Internal server error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return status deleted
|
||||||
|
c.Status(fiber.StatusOK)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handlePatchTranscription(c *fiber.Ctx) error {
|
||||||
|
var transcription models.Transcription
|
||||||
|
// Parse the body into the transcription struct.
|
||||||
|
err := json.Unmarshal(c.Body(), &transcription)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error parsing JSON body")
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "Bad request")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the transcription in the database
|
||||||
|
ut, err := s.Db.UpdateTranscription(&transcription)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msgf("Error updating transcription")
|
||||||
|
if err.Error() == "no documents were modified" {
|
||||||
|
return fiber.NewError(fiber.StatusNotModified, "Not found")
|
||||||
|
}
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Internal server error")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the JSON to the response body.
|
||||||
|
s.BroadcastTranscription(ut)
|
||||||
|
|
||||||
|
// Return status ok
|
||||||
|
json, err := json.Marshal(&ut)
|
||||||
|
if err != nil {
|
||||||
|
// 503 On vacation!
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Error parsing json!")
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(fiber.StatusOK)
|
||||||
|
c.Write(json)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleTranslate(c *fiber.Ctx) error {
|
||||||
|
id := c.Params("id")
|
||||||
|
targetLang := c.Params("target")
|
||||||
|
|
||||||
|
transcription := s.Db.GetTranscription(id)
|
||||||
|
|
||||||
|
// Set status as translating
|
||||||
|
transcription.Status = models.TrannscriptionStatusTranslating
|
||||||
|
s.Db.UpdateTranscription(transcription)
|
||||||
|
s.BroadcastTranscription(transcription)
|
||||||
|
|
||||||
|
err := transcription.Translate(targetLang)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error with translation")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set as done
|
||||||
|
transcription.Status = models.TranscriptionStatusDone
|
||||||
|
s.Db.UpdateTranscription(transcription)
|
||||||
|
s.BroadcastTranscription(transcription)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
158
backend/api/server.go
Normal file
158
backend/api/server.go
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/goccy/go-json"
|
||||||
|
"github.com/gofiber/contrib/websocket"
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/database"
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
ListenAddr string
|
||||||
|
Router *fiber.App
|
||||||
|
Db database.Db
|
||||||
|
NewTranscriptionCh chan bool
|
||||||
|
clients []*websocket.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServer(listenAddr string, db database.Db) *Server {
|
||||||
|
return &Server{
|
||||||
|
ListenAddr: listenAddr,
|
||||||
|
Router: fiber.New(fiber.Config{
|
||||||
|
JSONEncoder: json.Marshal,
|
||||||
|
JSONDecoder: json.Unmarshal,
|
||||||
|
BodyLimit: 100 * 1024 * 1024, // Increase body limit to 100MB
|
||||||
|
ServerHeader: "Fiber", // Optional, for easier debugging
|
||||||
|
}),
|
||||||
|
Db: db,
|
||||||
|
clients: make([]*websocket.Conn, 0),
|
||||||
|
NewTranscriptionCh: make(chan bool, 100),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) Run() {
|
||||||
|
s.SetupWebsocket()
|
||||||
|
s.SetupMiddleware()
|
||||||
|
s.RegisterRoutes()
|
||||||
|
s.Router.Listen(s.ListenAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) SetupWebsocket() {
|
||||||
|
s.Router.Get("/ws/transcriptions", websocket.New(func(c *websocket.Conn) {
|
||||||
|
|
||||||
|
// Add this connection to the slice of clients
|
||||||
|
s.clients = append(s.clients, c)
|
||||||
|
|
||||||
|
for {
|
||||||
|
_, msg, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
// Check for normal close error (1000) or going away error (1001)
|
||||||
|
if err.Error() != "websocket: close 1000 (normal)" &&
|
||||||
|
err.Error() != "websocket: close 1001 (going away)" {
|
||||||
|
log.Error().Err(err).Msgf("Error reading message")
|
||||||
|
}
|
||||||
|
// Remove the client from the slice if it has disconnected
|
||||||
|
s.clients = removeWsClient(s.clients, c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.handleWebsocketMessage(c, msg)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) BroadcastTranscription(t *models.Transcription) {
|
||||||
|
// Convert the transcription to JSON.
|
||||||
|
json, err := json.Marshal(&t)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error marshalling transcription to JSON:")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, client := range s.clients {
|
||||||
|
if err := client.WriteMessage(websocket.TextMessage, json); err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error broadcasting message:")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) SetupMiddleware() {
|
||||||
|
s.Router.Use(cors.New())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) RegisterRoutes() {
|
||||||
|
// Static routes
|
||||||
|
s.Router.Static("/api/video", os.Getenv("UPLOAD_DIR"))
|
||||||
|
|
||||||
|
// Register HTTP route for getting initial state.
|
||||||
|
s.Router.Get("/api/transcriptions", func(c *fiber.Ctx) error {
|
||||||
|
err := s.handleGetAllTranscriptions(c)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error handling POST /api/transcriptions")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
// Register HTTP route for getting initial state.
|
||||||
|
s.Router.Get("/api/transcriptions/:id", func(c *fiber.Ctx) error {
|
||||||
|
log.Debug().Msgf("GET /api/transcriptions/%v", c.Params("id"))
|
||||||
|
err := s.handleGetTranscriptionById(c)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error handling GET /api/transcriptions/:id")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
// Register HTTP route for getting initial state.
|
||||||
|
s.Router.Get("/api/translate/:id/:target", func(c *fiber.Ctx) error {
|
||||||
|
log.Debug().Msgf("GET /api/translate/%v/%v", c.Params("id"), c.Params("target"))
|
||||||
|
err := s.handleTranslate(c)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error handling GET /api/translate/:id/:source")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
// Register HTTP route for receiving the form data and creating new transcription job.
|
||||||
|
s.Router.Post("/api/transcriptions", func(c *fiber.Ctx) error {
|
||||||
|
log.Debug().Msg("POST /api/transcriptions")
|
||||||
|
err := s.handlePostTranscription(c)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error handling POST /api/transcriptions")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
s.Router.Patch("/api/transcriptions", func(c *fiber.Ctx) error {
|
||||||
|
//log.Debug().Msgf("PATCH /api/transcriptions/%v", c.Params("id"))
|
||||||
|
err := s.handlePatchTranscription(c)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error handling PATCH /api/transcriptions")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
// Register HTTP route for receiving the form data and creating new transcription job.
|
||||||
|
s.Router.Delete("/api/transcriptions/:id", func(c *fiber.Ctx) error {
|
||||||
|
log.Debug().Msgf("DELETE /api/transcriptions/%v", c.Params("id"))
|
||||||
|
err := s.handleDeleteTranscription(c)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error handling DELETE /api/transcriptions")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to remove a WebSocket connection from the slice
|
||||||
|
func removeWsClient(s []*websocket.Conn, r *websocket.Conn) []*websocket.Conn {
|
||||||
|
for i, v := range s {
|
||||||
|
if v == r {
|
||||||
|
return append(s[:i], s[i+1:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
41
backend/api/websocket.go
Normal file
41
backend/api/websocket.go
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/goccy/go-json"
|
||||||
|
"github.com/gofiber/contrib/websocket"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) handleWebsocketMessage(wsess *websocket.Conn, msg []byte) {
|
||||||
|
log.Info().Msgf("Received message from client: %v", wsess.RemoteAddr().String())
|
||||||
|
// Try to unmarshal message to transcription
|
||||||
|
var transcription models.Transcription
|
||||||
|
err := json.Unmarshal(msg, &transcription)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error unmarshalling message to transcription:")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var res *models.Transcription
|
||||||
|
// Check if the transcription has a valid ID
|
||||||
|
// If it has ID, it means it's an update
|
||||||
|
if transcription.ID != primitive.NilObjectID {
|
||||||
|
log.Printf("Updating transcription: %v", transcription.ID)
|
||||||
|
// Update transcription in database
|
||||||
|
res, err = s.Db.UpdateTranscription(&transcription)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error updating transcription in database:")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("Updated transcription in database: %v", res)
|
||||||
|
} else {
|
||||||
|
log.Error().Msgf("Transcription not updated, it does not have an ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// broadcast with gofiber websocket
|
||||||
|
s.BroadcastTranscription(res)
|
||||||
|
}
|
||||||
14
backend/database/database.go
Normal file
14
backend/database/database.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Db interface {
|
||||||
|
NewTranscription(*models.Transcription) (*models.Transcription, error)
|
||||||
|
UpdateTranscription(*models.Transcription) (*models.Transcription, error)
|
||||||
|
DeleteTranscription(string) error
|
||||||
|
GetTranscription(string) *models.Transcription
|
||||||
|
GetAllTranscriptions() []*models.Transcription
|
||||||
|
GetPendingTranscriptions() []*models.Transcription
|
||||||
|
}
|
||||||
166
backend/database/mongo.go
Normal file
166
backend/database/mongo.go
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MongoDb struct {
|
||||||
|
client *mongo.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMongoDb() *MongoDb {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(fmt.Sprintf("mongodb://root:example@%v", os.Getenv("DB_ENDPOINT"))))
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error connecting to mongodb")
|
||||||
|
}
|
||||||
|
return &MongoDb{
|
||||||
|
client: client,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MongoDb) GetTranscription(id string) *models.Transcription {
|
||||||
|
collection := m.client.Database("whishper").Collection("transcriptions")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
oid, err := primitive.ObjectIDFromHex(id)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error converting id to object id: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
filter := bson.D{primitive.E{Key: "_id", Value: oid}}
|
||||||
|
var result models.Transcription
|
||||||
|
err = collection.FindOne(ctx, filter).Decode(&result)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error getting transcription: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MongoDb) DeleteTranscription(id string) error {
|
||||||
|
collection := m.client.Database("whishper").Collection("transcriptions")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
oid, err := primitive.ObjectIDFromHex(id)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Msg("Error converting id to object id.")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
filter := bson.D{primitive.E{Key: "_id", Value: oid}}
|
||||||
|
_, err = collection.DeleteOne(ctx, filter)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Msg("Error deleting transcription")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MongoDb) NewTranscription(t *models.Transcription) (*models.Transcription, error) {
|
||||||
|
collection := m.client.Database("whishper").Collection("transcriptions")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
// Create a new mongodb object id
|
||||||
|
i, err := collection.InsertOne(ctx, t)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error creating new transcription: %v", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Set the id of the transcription to the mongodb object id
|
||||||
|
t.ID = i.InsertedID.(primitive.ObjectID)
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MongoDb) GetAllTranscriptions() []*models.Transcription {
|
||||||
|
collection := s.client.Database("whishper").Collection("transcriptions")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
cursor, err := collection.Find(ctx, bson.D{})
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error getting transcriptions: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer cursor.Close(ctx)
|
||||||
|
|
||||||
|
var transcriptions []*models.Transcription
|
||||||
|
for cursor.Next(ctx) {
|
||||||
|
var result models.Transcription
|
||||||
|
err := cursor.Decode(&result)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error decoding transcription: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
transcriptions = append(transcriptions, &result)
|
||||||
|
}
|
||||||
|
if err := cursor.Err(); err != nil {
|
||||||
|
log.Printf("Error getting transcriptions: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return transcriptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MongoDb) GetPendingTranscriptions() []*models.Transcription {
|
||||||
|
collection := s.client.Database("whishper").Collection("transcriptions")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
filter := bson.D{primitive.E{Key: "status", Value: models.TranscriptionStatusPending}}
|
||||||
|
cursor, err := collection.Find(ctx, filter)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error getting transcriptions: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
defer cursor.Close(ctx)
|
||||||
|
var transcriptions []*models.Transcription
|
||||||
|
for cursor.Next(ctx) {
|
||||||
|
var result models.Transcription
|
||||||
|
err := cursor.Decode(&result)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error decoding transcription: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
transcriptions = append(transcriptions, &result)
|
||||||
|
}
|
||||||
|
|
||||||
|
return transcriptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MongoDb) UpdateTranscription(t *models.Transcription) (*models.Transcription, error) {
|
||||||
|
collection := m.client.Database("whishper").Collection("transcriptions")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
filter := bson.D{primitive.E{Key: "_id", Value: t.ID}}
|
||||||
|
updateQuery := bson.D{primitive.E{Key: "$set", Value: t}}
|
||||||
|
updateResult, err := collection.UpdateOne(ctx, filter, updateQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if updateResult.MatchedCount == 0 {
|
||||||
|
return nil, errors.New("no documents matched the filter")
|
||||||
|
}
|
||||||
|
if updateResult.ModifiedCount == 0 {
|
||||||
|
return nil, errors.New("no documents were modified")
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
41
backend/go.mod
Normal file
41
backend/go.mod
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
module codeberg.org/pluja/whishper
|
||||||
|
|
||||||
|
go 1.20
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/goccy/go-json v0.10.2
|
||||||
|
github.com/gofiber/contrib/websocket v1.2.0
|
||||||
|
github.com/gofiber/fiber/v2 v2.48.0
|
||||||
|
github.com/rs/zerolog v1.30.0
|
||||||
|
go.mongodb.org/mongo-driver v1.12.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/andybalholm/brotli v1.0.5 // indirect
|
||||||
|
github.com/fasthttp/websocket v1.5.4 // indirect
|
||||||
|
github.com/golang/snappy v0.0.1 // indirect
|
||||||
|
github.com/google/go-cmp v0.5.6 // indirect
|
||||||
|
github.com/google/uuid v1.3.0 // indirect
|
||||||
|
github.com/h2non/filetype v1.1.3 // indirect
|
||||||
|
github.com/klauspost/compress v1.16.7 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||||
|
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
|
||||||
|
github.com/rivo/uniseg v0.2.0 // indirect
|
||||||
|
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee // indirect
|
||||||
|
github.com/snakesel/libretranslate v0.0.2 // indirect
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
|
github.com/valyala/fasthttp v1.48.0 // indirect
|
||||||
|
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||||
|
github.com/wader/goutubedl v0.0.0-20230817095831-89e825670ccd // indirect
|
||||||
|
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||||
|
github.com/xdg-go/scram v1.1.2 // indirect
|
||||||
|
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||||
|
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
|
||||||
|
golang.org/x/crypto v0.7.0 // indirect
|
||||||
|
golang.org/x/sync v0.1.0 // indirect
|
||||||
|
golang.org/x/sys v0.11.0 // indirect
|
||||||
|
golang.org/x/text v0.8.0 // indirect
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||||
|
)
|
||||||
114
backend/go.sum
Normal file
114
backend/go.sum
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
|
||||||
|
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||||
|
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/fasthttp/websocket v1.5.4 h1:Bq8HIcoiffh3pmwSKB8FqaNooluStLQQxnzQspMatgI=
|
||||||
|
github.com/fasthttp/websocket v1.5.4/go.mod h1:R2VXd4A6KBspb5mTrsWnZwn6ULkX56/Ktk8/0UNSJao=
|
||||||
|
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
|
||||||
|
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||||
|
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||||
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
|
github.com/gofiber/contrib/websocket v1.2.0 h1:E+GNxglSApjJCPwH1y3wLz69c1PuSvADwhMBeDc8Xxc=
|
||||||
|
github.com/gofiber/contrib/websocket v1.2.0/go.mod h1:Sf8RYFluiIKxONa/Kq0jk05EOUtqrb81pJopTxzcsX4=
|
||||||
|
github.com/gofiber/fiber/v2 v2.48.0 h1:cRVMCb9aUJDsyHxGFLwz/sGzDggdailZZyptU9F9cU0=
|
||||||
|
github.com/gofiber/fiber/v2 v2.48.0/go.mod h1:xqJgfqrc23FJuqGOW6DVgi3HyZEm2Mn9pRqUb2kHSX8=
|
||||||
|
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||||
|
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||||
|
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
|
||||||
|
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||||
|
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg=
|
||||||
|
github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
|
||||||
|
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||||
|
github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=
|
||||||
|
github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||||
|
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
|
||||||
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||||
|
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
|
||||||
|
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
|
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
|
||||||
|
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||||
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
|
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||||
|
github.com/rs/zerolog v1.30.0 h1:SymVODrcRsaRaSInD9yQtKbtWqwsfoPcRff/oRXLj4c=
|
||||||
|
github.com/rs/zerolog v1.30.0/go.mod h1:/tk+P47gFdPXq4QYjvCmT5/Gsug2nagsFWBWhAiSi1w=
|
||||||
|
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee h1:8Iv5m6xEo1NR1AvpV+7XmhI4r39LGNzwUL4YpMuL5vk=
|
||||||
|
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee/go.mod h1:qwtSXrKuJh/zsFQ12yEE89xfCrGKK63Rr7ctU/uCo4g=
|
||||||
|
github.com/snakesel/libretranslate v0.0.2 h1:6LG/UMMpGtoj3NXvlzsxZgQEH0Qsi62jCDd5Yq5ALL8=
|
||||||
|
github.com/snakesel/libretranslate v0.0.2/go.mod h1:B8F8Dda8RlkHRMzs/aw8DWj9HfyHSXpaJTFD391hEUI=
|
||||||
|
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
|
github.com/valyala/fasthttp v1.48.0 h1:oJWvHb9BIZToTQS3MuQ2R3bJZiNSa2KiNdeI8A+79Tc=
|
||||||
|
github.com/valyala/fasthttp v1.48.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
|
||||||
|
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||||
|
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||||
|
github.com/wader/goutubedl v0.0.0-20230817095831-89e825670ccd h1:XPyQDsvxm+Kawdk41tpvODAEcm24h9vVR/aZTI0tGAk=
|
||||||
|
github.com/wader/goutubedl v0.0.0-20230817095831-89e825670ccd/go.mod h1:5KXd5tImdbmz4JoVhePtbIokCwAfEhUVVx3WLHmjYuw=
|
||||||
|
github.com/wader/osleaktest v0.0.0-20191111175233-f643b0fed071/go.mod h1:XD6emOFPHVzb0+qQpiNOdPL2XZ0SRUM0N5JHuq6OmXo=
|
||||||
|
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||||
|
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||||
|
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
|
||||||
|
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
|
||||||
|
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||||
|
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||||
|
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||||
|
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
go.mongodb.org/mongo-driver v1.12.1 h1:nLkghSU8fQNaK7oUmDhQFsnrtcoNy7Z6LVFKsEecqgE=
|
||||||
|
go.mongodb.org/mongo-driver v1.12.1/go.mod h1:/rGBTebI3XYboVmgz+Wv3Bcbl3aD0QF9zl6kDDw18rQ=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||||
|
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
|
||||||
|
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||||
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
|
||||||
|
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
|
||||||
|
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
65
backend/main.go
Normal file
65
backend/main.go
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/api"
|
||||||
|
"codeberg.org/pluja/whishper/database"
|
||||||
|
"codeberg.org/pluja/whishper/monitor"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Logging
|
||||||
|
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||||
|
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||||
|
|
||||||
|
listenAddr := flag.String("addr", ":8080", "server listen address")
|
||||||
|
uploadDir := flag.String("updir", "/app/uploads", "upload directory")
|
||||||
|
asrEndpoint := flag.String("asr", "transcription-api:8000", "asr endpoint, i.e. localhost:9888")
|
||||||
|
dbHost := flag.String("db", "mongo:27017", "database endpoint host, i.e. localhost:27017")
|
||||||
|
translationEndpoint := flag.String("translation", "translate:5000", "translation endpoint, i.e. localhost:5000")
|
||||||
|
dev := flag.Bool("dev", false, "development mode")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
// Set environment variables
|
||||||
|
if os.Getenv("UPLOAD_DIR") == "" {
|
||||||
|
os.Setenv("UPLOAD_DIR", *uploadDir)
|
||||||
|
}
|
||||||
|
if os.Getenv("ASR_ENDPOINT") == "" {
|
||||||
|
os.Setenv("ASR_ENDPOINT", *asrEndpoint)
|
||||||
|
}
|
||||||
|
if os.Getenv("TRANSLATION_ENDPOINT") == "" {
|
||||||
|
os.Setenv("TRANSLATION_ENDPOINT", *translationEndpoint)
|
||||||
|
}
|
||||||
|
if os.Getenv("DB_ENDPOINT") == "" {
|
||||||
|
os.Setenv("DB_ENDPOINT", *dbHost)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure dev mode
|
||||||
|
if *dev {
|
||||||
|
log.Logger = log.Output(
|
||||||
|
zerolog.ConsoleWriter{
|
||||||
|
Out: os.Stdout,
|
||||||
|
TimeFormat: "15:04:05",
|
||||||
|
},
|
||||||
|
).With().Caller().Logger()
|
||||||
|
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("DEV MODE IS ON")
|
||||||
|
log.Debug().Msgf("ListenAddr: %v", *listenAddr)
|
||||||
|
log.Debug().Msgf("UploadDir: %v", *uploadDir)
|
||||||
|
log.Debug().Msgf("AsrEndpoint: %v", *asrEndpoint)
|
||||||
|
log.Debug().Msgf("TranslationEndpoint: %v", *translationEndpoint)
|
||||||
|
log.Debug().Msgf("DbHost: %v", *dbHost)
|
||||||
|
|
||||||
|
dabs := database.NewMongoDb()
|
||||||
|
server := api.NewServer(*listenAddr, dabs)
|
||||||
|
go monitor.StartMonitor(server)
|
||||||
|
server.NewTranscriptionCh <- true
|
||||||
|
server.Run()
|
||||||
|
}
|
||||||
14
backend/models/constants.go
Normal file
14
backend/models/constants.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
const (
|
||||||
|
TranscriptionStatusPending = 0
|
||||||
|
TranscriptionStatusRunning = 1
|
||||||
|
TranscriptionStatusDone = 2
|
||||||
|
TrannscriptionStatusTranslating = 3
|
||||||
|
TranscriptionStatusError = -1
|
||||||
|
|
||||||
|
SourceTypeFile = "file"
|
||||||
|
SourceTypeURL = "url"
|
||||||
|
|
||||||
|
FileNameSeparator = "_WHSHPR_"
|
||||||
|
)
|
||||||
67
backend/models/transcription.go
Normal file
67
backend/models/transcription.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
ltr "github.com/snakesel/libretranslate"
|
||||||
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Transcription struct {
|
||||||
|
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
|
||||||
|
Status int `bson:"status" json:"status"`
|
||||||
|
Language string `bson:"language" json:"language"`
|
||||||
|
ModelSize string `bson:"modelSize" json:"modelSize"`
|
||||||
|
Task string `bson:"task" json:"task"`
|
||||||
|
Device string `bson:"device" json:"device"`
|
||||||
|
FileName string `bson:"fileName" json:"fileName"`
|
||||||
|
SourceUrl string `bson:"sourceUrl" json:"sourceUrl"`
|
||||||
|
Result WhisperResult `bson:"result" json:"result"`
|
||||||
|
Translations []Translation `bson:"translations" json:"translations"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Transcription) Translate(target string) error {
|
||||||
|
for _, translation := range t.Translations {
|
||||||
|
if translation.TargetLanguage == target {
|
||||||
|
log.Debug().Msgf("Translation for %v already exists!", target)
|
||||||
|
return fmt.Errorf("translation for %v already exists", target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
translate := ltr.New(ltr.Config{
|
||||||
|
Url: fmt.Sprintf("http://%v", os.Getenv("TRANSLATION_ENDPOINT")),
|
||||||
|
})
|
||||||
|
|
||||||
|
var translation Translation
|
||||||
|
translation.SourceLanguage = t.Language
|
||||||
|
translation.TargetLanguage = target
|
||||||
|
|
||||||
|
trtext, err := translate.Translate(t.Result.Text, translation.SourceLanguage, translation.TargetLanguage)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msgf("Error translating text...")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
translatedText := trtext
|
||||||
|
|
||||||
|
translatedSegments := make([]Segment, len(t.Result.Segments))
|
||||||
|
copy(translatedSegments, t.Result.Segments)
|
||||||
|
for i, seg := range t.Result.Segments {
|
||||||
|
trtext, err := translate.Translate(seg.Text, translation.SourceLanguage, translation.TargetLanguage)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msgf("Error translating segment text...")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
translatedSegments[i].Text = trtext
|
||||||
|
// Word-level data is lost, since we can't make sure that words will be in the same order and number as the final translation.
|
||||||
|
// For example, if we translate "The big home" to Spanish, we could get "La casa grande", thus words changed order.
|
||||||
|
translatedSegments[i].Words = []Word{}
|
||||||
|
}
|
||||||
|
|
||||||
|
translation.Result.Text = translatedText
|
||||||
|
translation.Result.Segments = translatedSegments
|
||||||
|
translation.Result.Language = translation.TargetLanguage
|
||||||
|
t.Translations = append(t.Translations, translation)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
8
backend/models/translation.go
Normal file
8
backend/models/translation.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
type Translation struct {
|
||||||
|
SourceLanguage string `json:"sourceLanguage"`
|
||||||
|
TargetLanguage string `json:"targetLanguage"`
|
||||||
|
Status int `json:"translationStatus"`
|
||||||
|
Result WhisperResult `json:"result"`
|
||||||
|
}
|
||||||
24
backend/models/whisper.go
Normal file
24
backend/models/whisper.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
type WhisperResult struct {
|
||||||
|
Language string `json:"language"`
|
||||||
|
Duration float64 `json:"duration"`
|
||||||
|
Segments []Segment `json:"segments"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Segment struct {
|
||||||
|
End float64 `json:"end"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Start float64 `json:"start"`
|
||||||
|
Score float64 `json:"score"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Words []Word `json:"words"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Word struct {
|
||||||
|
End float64 `json:"end"`
|
||||||
|
Start float64 `json:"start"`
|
||||||
|
Word string `json:"word"`
|
||||||
|
Score float64 `json:"score"`
|
||||||
|
}
|
||||||
126
backend/monitor/monitor.go
Normal file
126
backend/monitor/monitor.go
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
package monitor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/api"
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
"codeberg.org/pluja/whishper/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
func StartMonitor(s *api.Server) {
|
||||||
|
log.Info().Msg("Starting monitor!")
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
// Wait for new transcription to be added to the database
|
||||||
|
// notification will be received through the NewTranscriptionCh channel
|
||||||
|
<-s.NewTranscriptionCh
|
||||||
|
pendingTranscriptions := s.Db.GetPendingTranscriptions()
|
||||||
|
log.Debug().Msgf("Pending transcriptions: %v", len(pendingTranscriptions))
|
||||||
|
for _, pt := range pendingTranscriptions {
|
||||||
|
log.Debug().Msgf("Taking pending transcription %v", pt.ID)
|
||||||
|
if pt.Status == models.TranscriptionStatusPending {
|
||||||
|
err := transcribe(s, pt)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error transcribing")
|
||||||
|
pt.Status = models.TranscriptionStatusError
|
||||||
|
ut, err := s.Db.UpdateTranscription(pt)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error updating transcription")
|
||||||
|
}
|
||||||
|
s.BroadcastTranscription(ut)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func transcribe(s *api.Server, t *models.Transcription) error {
|
||||||
|
// Update transcription status
|
||||||
|
t.Status = models.TranscriptionStatusRunning
|
||||||
|
log.Debug().Msgf("Updating transcription %v", t)
|
||||||
|
_, err := s.Db.UpdateTranscription(t)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error updating transcription")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.BroadcastTranscription(t)
|
||||||
|
|
||||||
|
if t.SourceUrl != "" {
|
||||||
|
// Download media
|
||||||
|
fn, err := utils.DownloadMedia(t)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error downloading media")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t.FileName = fn
|
||||||
|
s.BroadcastTranscription(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare multipart form data
|
||||||
|
body, writer, err := prepareMultipartFormData(t)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error preparing multipart form data")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send transcription request to transcription service
|
||||||
|
res, err := utils.SendTranscriptionRequest(t, body, writer)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error sending transcription request")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Result = *res
|
||||||
|
t.Translations = []models.Translation{}
|
||||||
|
t.Status = models.TranscriptionStatusDone
|
||||||
|
_, err = s.Db.UpdateTranscription(t)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error updating transcription")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.BroadcastTranscription(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareMultipartFormData(t *models.Transcription) (*bytes.Buffer, *multipart.Writer, error) {
|
||||||
|
body := &bytes.Buffer{}
|
||||||
|
writer := multipart.NewWriter(body)
|
||||||
|
|
||||||
|
part, err := writer.CreateFormFile("file", t.FileName)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error creating form file")
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read file from disk
|
||||||
|
filePath := filepath.Join(os.Getenv("UPLOAD_DIR"), t.FileName)
|
||||||
|
file, err := os.Open(filePath)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error opening file")
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
_, err = io.Copy(part, file)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error copying file")
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = writer.Close()
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Error closing writer")
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return body, writer, nil
|
||||||
|
}
|
||||||
111
backend/utils/utils.go
Normal file
111
backend/utils/utils.go
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"github.com/wader/goutubedl"
|
||||||
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
|
|
||||||
|
"codeberg.org/pluja/whishper/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SanitizeFilename(filename string) string {
|
||||||
|
// First remove trailing spaces
|
||||||
|
filename = strings.TrimSpace(filename)
|
||||||
|
// Then remove quotes and dots
|
||||||
|
filename = strings.Trim(filename, `"'.`)
|
||||||
|
reg, _ := regexp.Compile("[^a-zA-Z0-9]+")
|
||||||
|
filename = reg.ReplaceAllString(filename, "_")
|
||||||
|
return filename
|
||||||
|
}
|
||||||
|
|
||||||
|
func DownloadMedia(t *models.Transcription) (string, error) {
|
||||||
|
if t.SourceUrl == "" {
|
||||||
|
log.Debug().Msg("Source URL is empty")
|
||||||
|
return "", fmt.Errorf("source URL is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.ID == primitive.NilObjectID {
|
||||||
|
log.Debug().Msg("Transcription ID is empty")
|
||||||
|
return "", fmt.Errorf("transcription ID is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
goutubedl.Path = "yt-dlp"
|
||||||
|
result, err := goutubedl.New(context.Background(), t.SourceUrl, goutubedl.Options{})
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error creating goutubedl")
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
downloadResult, err := result.Download(context.Background(), "best")
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error downloading media")
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
filename := fmt.Sprintf("%v%v%v", t.ID.Hex(), models.FileNameSeparator, result.Info.Title)
|
||||||
|
filename = SanitizeFilename(filename)
|
||||||
|
|
||||||
|
defer downloadResult.Close()
|
||||||
|
f, err := os.Create(filepath.Join(os.Getenv("UPLOAD_DIR"), filename))
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error creating file")
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
io.Copy(f, downloadResult)
|
||||||
|
|
||||||
|
return filename, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SendTranscriptionRequest(t *models.Transcription, body *bytes.Buffer, writer *multipart.Writer) (*models.WhisperResult, error) {
|
||||||
|
url := fmt.Sprintf("http://%v/transcribe?model_size=%v&task=%v&language=%v&device=%v", os.Getenv("ASR_ENDPOINT"), t.ModelSize, t.Task, t.Language, t.Device)
|
||||||
|
// Send transcription request to transcription service
|
||||||
|
req, err := http.NewRequest("POST", url, body)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error creating request to transcription service")
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
client := &http.Client{}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error sending request")
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
b, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error reading response body")
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
log.Debug().Msgf("Response from %v: %v", url, string(b))
|
||||||
|
log.Debug().Err(err).Msgf("Invalid response status %v:", resp.StatusCode)
|
||||||
|
return nil, errors.New("invalid status")
|
||||||
|
}
|
||||||
|
|
||||||
|
var asrResponse *models.WhisperResult
|
||||||
|
if err := json.Unmarshal(b, &asrResponse); err != nil {
|
||||||
|
log.Debug().Err(err).Msg("Error decoding response")
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return asrResponse, nil
|
||||||
|
|
||||||
|
}
|
||||||
115
docker-compose.yml
Normal file
115
docker-compose.yml
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
version: "3.9"
|
||||||
|
|
||||||
|
services:
|
||||||
|
mongo:
|
||||||
|
image: mongo
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
- ./whishper_data/db_data:/data/db
|
||||||
|
- ./whishper_data/db_data/logs/:/var/log/mongodb/
|
||||||
|
environment:
|
||||||
|
MONGO_INITDB_ROOT_USERNAME: root
|
||||||
|
MONGO_INITDB_ROOT_PASSWORD: example
|
||||||
|
expose:
|
||||||
|
- 27017
|
||||||
|
command: ['--logpath', '/var/log/mongodb/mongod.log']
|
||||||
|
healthcheck:
|
||||||
|
test: mongosh --eval 'db.runCommand("ping").ok' --quiet
|
||||||
|
interval: 15s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 5
|
||||||
|
start_period: 5s
|
||||||
|
|
||||||
|
translate:
|
||||||
|
container_name: whisper-libretranslate
|
||||||
|
image: libretranslate/libretranslate:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./whishper_data/libretranslate/data:/home/libretranslate/.local/share
|
||||||
|
- ./whishper_data/libretranslate/cache:/home/libretranslate/.local/cache
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
tty: true
|
||||||
|
environment:
|
||||||
|
LT_DISABLE_WEB_UI: True
|
||||||
|
#LT_UPDATE_MODELS: True
|
||||||
|
expose:
|
||||||
|
- 5000
|
||||||
|
healthcheck:
|
||||||
|
test: ['CMD-SHELL', './venv/bin/python scripts/healthcheck.py']
|
||||||
|
interval: 15s
|
||||||
|
timeout: 10s
|
||||||
|
start_period: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
transcription-api:
|
||||||
|
container_name: whisper-api
|
||||||
|
build: ./transcription-api
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
volumes:
|
||||||
|
- ./whishper_data/whisper_models:/app/models
|
||||||
|
- ./whishper_data/uploads:/app/uploads
|
||||||
|
environment:
|
||||||
|
- WHISPER_MODELS_DIR=/app/models
|
||||||
|
- UPLOAD_DIR=/app/uploads
|
||||||
|
restart: unless-stopped
|
||||||
|
expose:
|
||||||
|
- 8000
|
||||||
|
|
||||||
|
whishper-backend:
|
||||||
|
container_name: whishper-backend
|
||||||
|
build: ./backend
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
volumes:
|
||||||
|
- ./whishper_data/uploads:/app/uploads
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
mongo:
|
||||||
|
condition: service_healthy
|
||||||
|
translate:
|
||||||
|
condition: service_healthy
|
||||||
|
transcription-api:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: curl --fail http://localhost:8080/api/transcriptions || exit 1
|
||||||
|
interval: 15s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 5
|
||||||
|
start_period: 5s
|
||||||
|
expose:
|
||||||
|
- 8080
|
||||||
|
|
||||||
|
whishper-frontend:
|
||||||
|
container_name: whishper-web
|
||||||
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
args:
|
||||||
|
PUBLIC_API_HOST: ${WHISHPER_PUBLIC_URL}
|
||||||
|
PUBLIC_TRANSLATION_API_HOST: ""
|
||||||
|
PUBLIC_INTERNAL_API_HOST: "http://nginx:80"
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
PUBLIC_INTERNAL_API_HOST: "http://nginx:80"
|
||||||
|
PUBLIC_TRANSLATION_API_HOST: ""
|
||||||
|
PUBLIC_API_HOST: ${WHISHPER_PUBLIC_URL}
|
||||||
|
depends_on:
|
||||||
|
transcription-api:
|
||||||
|
condition: service_healthy
|
||||||
|
expose:
|
||||||
|
- 3000
|
||||||
|
|
||||||
|
nginx:
|
||||||
|
image: nginx:1
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./nginx.conf:/etc/nginx/nginx.conf
|
||||||
|
- ./whishper_data/uploads:/app/uploads
|
||||||
|
depends_on:
|
||||||
|
whishper-backend:
|
||||||
|
condition: service_healthy
|
||||||
|
ports:
|
||||||
|
- 8082:80
|
||||||
5
example.env
Normal file
5
example.env
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# Libretranslate Configuration
|
||||||
|
LT_LOAD_ONLY=es,en,fr
|
||||||
|
# Whisper Configuration
|
||||||
|
WHISPER_MODELS=tiny,small
|
||||||
|
WHISHPER_HOST=localhost:8082
|
||||||
8
frontend/.dockerignore
Normal file
8
frontend/.dockerignore
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
.env
|
||||||
|
node_modules/
|
||||||
|
.svelte-kit
|
||||||
|
Dockerfile
|
||||||
|
.eslintignore
|
||||||
|
.eslintrc.js
|
||||||
|
.prettierrc
|
||||||
|
.gitignore
|
||||||
13
frontend/.eslintignore
Normal file
13
frontend/.eslintignore
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
.DS_Store
|
||||||
|
node_modules
|
||||||
|
/build
|
||||||
|
/.svelte-kit
|
||||||
|
/package
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# Ignore files for PNPM, NPM and YARN
|
||||||
|
pnpm-lock.yaml
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
14
frontend/.eslintrc.cjs
Normal file
14
frontend/.eslintrc.cjs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
module.exports = {
|
||||||
|
root: true,
|
||||||
|
extends: ['eslint:recommended', 'plugin:svelte/recommended', 'prettier'],
|
||||||
|
parserOptions: {
|
||||||
|
sourceType: 'module',
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
extraFileExtensions: ['.svelte']
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
browser: true,
|
||||||
|
es2017: true,
|
||||||
|
node: true
|
||||||
|
}
|
||||||
|
};
|
||||||
10
frontend/.gitignore
vendored
Normal file
10
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
.DS_Store
|
||||||
|
node_modules
|
||||||
|
build/
|
||||||
|
/.svelte-kit
|
||||||
|
/package
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
vite.config.js.timestamp-*
|
||||||
|
vite.config.ts.timestamp-*
|
||||||
2
frontend/.npmrc
Normal file
2
frontend/.npmrc
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
engine-strict=true
|
||||||
|
resolution-mode=highest
|
||||||
13
frontend/.prettierignore
Normal file
13
frontend/.prettierignore
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
.DS_Store
|
||||||
|
node_modules
|
||||||
|
/build
|
||||||
|
/.svelte-kit
|
||||||
|
/package
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# Ignore files for PNPM, NPM and YARN
|
||||||
|
pnpm-lock.yaml
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
9
frontend/.prettierrc
Normal file
9
frontend/.prettierrc
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"useTabs": true,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "none",
|
||||||
|
"printWidth": 100,
|
||||||
|
"plugins": ["prettier-plugin-svelte"],
|
||||||
|
"pluginSearchDirs": ["."],
|
||||||
|
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||||
|
}
|
||||||
34
frontend/Dockerfile
Normal file
34
frontend/Dockerfile
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
FROM node:alpine as build
|
||||||
|
|
||||||
|
ARG PUBLIC_API_HOST
|
||||||
|
ARG PUBLIC_TRANSLATION_API_HOST
|
||||||
|
ARG PUBLIC_INTERNAL_API_HOST
|
||||||
|
|
||||||
|
ENV PUBLIC_API_HOST=$PUBLIC_API_HOST
|
||||||
|
ENV PUBLIC_TRANSLATION_API_HOST=$PUBLIC_TRANSLATION_API_HOST
|
||||||
|
ENV PUBLIC_INTERNAL_API_HOST=$PUBLIC_INTERNAL_API_HOST
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . .
|
||||||
|
RUN yarn
|
||||||
|
ENV BODY_SIZE_LIMIT=0
|
||||||
|
RUN yarn build
|
||||||
|
RUN ls -al
|
||||||
|
|
||||||
|
FROM node:alpine as production
|
||||||
|
|
||||||
|
ARG PUBLIC_API_HOST
|
||||||
|
ARG PUBLIC_TRANSLATION_API_HOST
|
||||||
|
ARG PUBLIC_INTERNAL_API_HOST
|
||||||
|
|
||||||
|
ENV PUBLIC_API_HOST=$PUBLIC_API_HOST
|
||||||
|
ENV PUBLIC_TRANSLATION_API_HOST=$PUBLIC_TRANSLATION_API_HOST
|
||||||
|
ENV PUBLIC_INTERNAL_API_HOST=$PUBLIC_INTERNAL_API_HOST
|
||||||
|
ENV BODY_SIZE_LIMIT=0
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=build /app/package.json ./
|
||||||
|
COPY --from=build /app/build/ ./
|
||||||
|
RUN yarn --production
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD [ "node", "index.js"]
|
||||||
38
frontend/README.md
Normal file
38
frontend/README.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# create-svelte
|
||||||
|
|
||||||
|
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
|
||||||
|
|
||||||
|
## Creating a project
|
||||||
|
|
||||||
|
If you're seeing this, you've probably already done this step. Congrats!
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# create a new project in the current directory
|
||||||
|
npm create svelte@latest
|
||||||
|
|
||||||
|
# create a new project in my-app
|
||||||
|
npm create svelte@latest my-app
|
||||||
|
```
|
||||||
|
|
||||||
|
## Developing
|
||||||
|
|
||||||
|
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# or start the server and open the app in a new browser tab
|
||||||
|
npm run dev -- --open
|
||||||
|
```
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
To create a production version of your app:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
You can preview the production build with `npm run preview`.
|
||||||
|
|
||||||
|
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
|
||||||
32
frontend/package.json
Normal file
32
frontend/package.json
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite dev",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"lint": "prettier --plugin-search-dir . --check . && eslint .",
|
||||||
|
"format": "prettier --plugin-search-dir . --write ."
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@sveltejs/adapter-auto": "^2.0.0",
|
||||||
|
"@sveltejs/adapter-node": "^1.3.1",
|
||||||
|
"@sveltejs/kit": "^1.20.4",
|
||||||
|
"autoprefixer": "^10.4.15",
|
||||||
|
"daisyui": "^3.5.1",
|
||||||
|
"eslint": "^8.28.0",
|
||||||
|
"eslint-config-prettier": "^8.5.0",
|
||||||
|
"eslint-plugin-svelte": "^2.30.0",
|
||||||
|
"postcss": "^8.4.28",
|
||||||
|
"prettier": "^2.8.0",
|
||||||
|
"prettier-plugin-svelte": "^2.10.1",
|
||||||
|
"svelte": "^4.0.5",
|
||||||
|
"tailwindcss": "^3.3.3",
|
||||||
|
"vite": "^4.4.2"
|
||||||
|
},
|
||||||
|
"type": "module",
|
||||||
|
"dependencies": {
|
||||||
|
"svelte-french-toast": "^1.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
frontend/postcss.config.js
Normal file
6
frontend/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
3
frontend/src/app.css
Normal file
3
frontend/src/app.css
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
13
frontend/src/app.html
Normal file
13
frontend/src/app.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en" data-theme="dark">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="%sveltekit.assets%/favicon.webp" />
|
||||||
|
<meta name="viewport" content="width=device-width" />
|
||||||
|
<title>Whishper</title>
|
||||||
|
%sveltekit.head%
|
||||||
|
</head>
|
||||||
|
<body data-sveltekit-preload-data="hover">
|
||||||
|
<div style="display: contents">%sveltekit.body%</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
282
frontend/src/lib/components/Editor.svelte
Normal file
282
frontend/src/lib/components/Editor.svelte
Normal file
@@ -0,0 +1,282 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount, onDestroy } from 'svelte';
|
||||||
|
import { writable } from 'svelte/store';
|
||||||
|
import toast from 'svelte-french-toast';
|
||||||
|
import { editorSettings, currentTranscription, editorHistory } from '$lib/stores';
|
||||||
|
import EditorSettings from './EditorSettings.svelte';
|
||||||
|
import EditorSegment from './EditorSegment.svelte';
|
||||||
|
import { CLIENT_API_HOST } from '$lib/utils';
|
||||||
|
|
||||||
|
|
||||||
|
let language = writable('original');
|
||||||
|
|
||||||
|
// Segments lazy loading
|
||||||
|
let segmentsToShow = 20;
|
||||||
|
function loadMore() {
|
||||||
|
segmentsToShow += 10;
|
||||||
|
}
|
||||||
|
let loadMoreButton;
|
||||||
|
|
||||||
|
async function textFromSegments() {
|
||||||
|
let text = '';
|
||||||
|
if ($language == 'original') {
|
||||||
|
text = $currentTranscription.result.segments
|
||||||
|
.map((segment) => segment.text)
|
||||||
|
.join(' ')
|
||||||
|
.replace(/(\r\n|\n|\r)/gm, ' ');
|
||||||
|
} else {
|
||||||
|
text = $currentTranscription.translations
|
||||||
|
.filter((translation) => translation.targetLanguage == $language)[0]
|
||||||
|
.result.segments.map((segment) => segment.text)
|
||||||
|
.join(' ')
|
||||||
|
.replace(/(\r\n|\n|\r)/gm, ' ');
|
||||||
|
}
|
||||||
|
console.log(text);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveChanges() {
|
||||||
|
var url = `${CLIENT_API_HOST}/api/transcriptions`; // replace with your actual endpoint
|
||||||
|
console.log($language)
|
||||||
|
// Update text to match segments
|
||||||
|
if ($language == 'original') {
|
||||||
|
$currentTranscription.result.text = await textFromSegments();
|
||||||
|
} else {
|
||||||
|
$currentTranscription.translations.forEach(async (translation) => {
|
||||||
|
if (translation.targetLanguage == $language) translation.result.text = await textFromSegments();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify($currentTranscription)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 304) {
|
||||||
|
if (!$editorSettings.autoSave) {
|
||||||
|
toast('No changes were made!', {
|
||||||
|
icon: '👐'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
toast.error("Couldn't save!");
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($editorSettings.autoSave) {
|
||||||
|
toast('Autosaving...', { icon: 'ℹ️' });
|
||||||
|
} else {
|
||||||
|
toast.success('Saved!');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
toast.error("Couldn't save!");
|
||||||
|
console.error('Error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let handleKeyDown;
|
||||||
|
let observer;
|
||||||
|
onMount(() => {
|
||||||
|
// Lazy loading
|
||||||
|
observer = new IntersectionObserver((entries) => {
|
||||||
|
entries.forEach((entry) => {
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
loadMore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
observer.observe(loadMoreButton);
|
||||||
|
|
||||||
|
// Function to handle Ctrl+Z and Ctrl+S shortcuts
|
||||||
|
editorHistory.set([JSON.parse(JSON.stringify($currentTranscription))]);
|
||||||
|
let isUndoing = false;
|
||||||
|
handleKeyDown = function (e) {
|
||||||
|
// Undo (CTRL+Z)
|
||||||
|
if (e.ctrlKey && e.key === 'z' && !isUndoing) {
|
||||||
|
isUndoing = true;
|
||||||
|
let previousTranscription = null;
|
||||||
|
|
||||||
|
editorHistory.update((history) => {
|
||||||
|
if (history.length > 1) {
|
||||||
|
history = history.slice(0, -1);
|
||||||
|
previousTranscription = { ...history[history.length - 1] };
|
||||||
|
}
|
||||||
|
return history;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (previousTranscription) {
|
||||||
|
$currentTranscription = { ...previousTranscription };
|
||||||
|
}
|
||||||
|
isUndoing = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let isSaving = false;
|
||||||
|
if (e.ctrlKey && e.key === 's') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!isSaving) {
|
||||||
|
isSaving = true;
|
||||||
|
saveChanges();
|
||||||
|
isSaving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!$editorSettings.autoSave) {
|
||||||
|
toast('Autosave is disabled.', {
|
||||||
|
icon: '👋'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listen to keydown event
|
||||||
|
document.addEventListener('keydown', handleKeyDown);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Autosave
|
||||||
|
let autosaveInterval;
|
||||||
|
let autoSaveAux = $editorSettings.autoSave;
|
||||||
|
$: if ($editorSettings.autoSave) {
|
||||||
|
toast.success('Autosave enabled.');
|
||||||
|
autoSaveAux = true;
|
||||||
|
autosaveInterval = setInterval(() => {
|
||||||
|
saveChanges();
|
||||||
|
}, $editorSettings.autosaveInterval);
|
||||||
|
} else {
|
||||||
|
if (autoSaveAux == true) {
|
||||||
|
toast('Autosave is disabled.', {
|
||||||
|
icon: '👋'
|
||||||
|
});
|
||||||
|
autoSaveAux = false;
|
||||||
|
}
|
||||||
|
clearInterval(autosaveInterval);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if $currentTranscription.status != 2}
|
||||||
|
<div class="flex items-center justify-center">
|
||||||
|
<span class="loading loading-spinner loading-lg"></span>
|
||||||
|
<p class="text-center">Waiting for task to finish {$currentTranscription.status == 3 ? "translating" : "transcribing"}...</p>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="flex flex-col items-center break-words">
|
||||||
|
<h1 class="text-center text-2xl mt-8 break-words">
|
||||||
|
{$currentTranscription.fileName.split('_WHSHPR_')[1]}
|
||||||
|
</h1>
|
||||||
|
<!-- Menu -->
|
||||||
|
<ul class="menu menu-horizontal bg-base-200 rounded-box mt-6">
|
||||||
|
<li>
|
||||||
|
<a href="/" class="tooltip" data-tip="Home">
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="h-5 w-5"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
><path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
|
||||||
|
/></svg
|
||||||
|
>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<button on:click={saveChanges} class="tooltip" data-tip="Save (Ctrl+S)">
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="icon icon-tabler icon-tabler-device-floppy"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path d="M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2" />
|
||||||
|
<path d="M12 14m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" />
|
||||||
|
<path d="M14 4l0 4l-6 0l0 -4" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<!-- End Menu -->
|
||||||
|
|
||||||
|
{#if $currentTranscription.translations.length > 0}
|
||||||
|
<div class="form-control max-w-xs my-4">
|
||||||
|
<label for="language" class="label">
|
||||||
|
<span class="label-text">Subtitles language</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
bind:value={$language}
|
||||||
|
name="language"
|
||||||
|
class="select select-sm select-bordered uppercase"
|
||||||
|
>
|
||||||
|
<option value="original">✅ {$currentTranscription.result.language}</option>
|
||||||
|
{#each $currentTranscription.translations as translation}
|
||||||
|
<option value={translation.targetLanguage}>🤖 {translation.targetLanguage}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="mt-4">
|
||||||
|
<!-- Editor configuration -->
|
||||||
|
<EditorSettings />
|
||||||
|
<!-- End Editor configuration -->
|
||||||
|
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<!-- Segments table -->
|
||||||
|
<table class="table px-4">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th />
|
||||||
|
<th>Start</th>
|
||||||
|
<th>End</th>
|
||||||
|
<th>Text</th>
|
||||||
|
<th>Info</th>
|
||||||
|
<th />
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{#if $language == 'original'}
|
||||||
|
{#each $currentTranscription.result.segments.slice(0, segmentsToShow) as segment, index (segment.id)}
|
||||||
|
<EditorSegment {segment} {index} translationIndex={-1} />
|
||||||
|
{/each}
|
||||||
|
{:else}
|
||||||
|
{#each $currentTranscription.translations as translation, translationIndex}
|
||||||
|
{#if translation.targetLanguage == $language}
|
||||||
|
{#each translation.result.segments.slice(0, segmentsToShow) as segment, index (segment.id)}
|
||||||
|
<EditorSegment {segment} {index} {translationIndex} />
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<button bind:this={loadMoreButton}>
|
||||||
|
{#if $language == 'original'}
|
||||||
|
{#if segmentsToShow >= $currentTranscription.result.segments.length}
|
||||||
|
No more segments to load
|
||||||
|
{:else}
|
||||||
|
Loading more...
|
||||||
|
{/if}
|
||||||
|
{:else if segmentsToShow >= $currentTranscription.translations.filter((translation) => translation.targetLanguage == $language)[0].result.segments.length}
|
||||||
|
No more segments to load
|
||||||
|
{:else}
|
||||||
|
Loading more...
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
<!-- End Segments table -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
354
frontend/src/lib/components/EditorSegment.svelte
Normal file
354
frontend/src/lib/components/EditorSegment.svelte
Normal file
@@ -0,0 +1,354 @@
|
|||||||
|
<script>
|
||||||
|
import { editorSettings } from '$lib/stores';
|
||||||
|
import { currentVideoPlayerTime, currentTranscription, editorHistory } from '$lib/stores';
|
||||||
|
export let index;
|
||||||
|
export let segment;
|
||||||
|
export let translationIndex;
|
||||||
|
|
||||||
|
let isActive = false;
|
||||||
|
|
||||||
|
function getCps(s) {
|
||||||
|
// Find duration
|
||||||
|
let duration = s.end - s.start;
|
||||||
|
|
||||||
|
// Count characters
|
||||||
|
let charCount = s.text.length;
|
||||||
|
|
||||||
|
// Calculate CPS
|
||||||
|
let cps = charCount / duration;
|
||||||
|
|
||||||
|
// Round to 2 decimals
|
||||||
|
cps = Math.round(cps * 100) / 100;
|
||||||
|
// Truncate to integer
|
||||||
|
return Math.trunc(cps);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteSegment(index, callback) {
|
||||||
|
console.log($currentTranscription)
|
||||||
|
const source =
|
||||||
|
translationIndex == -1
|
||||||
|
? $currentTranscription.result.segments
|
||||||
|
: $currentTranscription.translations[translationIndex].result.segments;
|
||||||
|
source.splice(index, 1);
|
||||||
|
// Update index
|
||||||
|
$currentTranscription = { ...$currentTranscription }; // deep copy
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
|
||||||
|
// This function takes a segment and splits it into two segments at the given index
|
||||||
|
function splitSegment(index, callback) {
|
||||||
|
// Choose the correct source based on translationIndex
|
||||||
|
const source =
|
||||||
|
translationIndex == -1
|
||||||
|
? $currentTranscription.result.segments
|
||||||
|
: $currentTranscription.translations[translationIndex].result.segments;
|
||||||
|
|
||||||
|
const segment = source[index];
|
||||||
|
const words = segment.text.split(' ');
|
||||||
|
const half = Math.ceil(words.length / 2);
|
||||||
|
const firstHalf = words.slice(0, half).join(' ');
|
||||||
|
const secondHalf = words.slice(half).join(' ');
|
||||||
|
|
||||||
|
const duration = segment.end - segment.start;
|
||||||
|
const midTime = segment.start + duration / 2;
|
||||||
|
|
||||||
|
// Update current segment
|
||||||
|
segment.text = firstHalf;
|
||||||
|
segment.end = midTime;
|
||||||
|
|
||||||
|
// Create and insert new segment
|
||||||
|
const newSegment = {
|
||||||
|
id: JSON.stringify(Date.now()),
|
||||||
|
start: midTime,
|
||||||
|
end: segment.end + duration / 2,
|
||||||
|
text: secondHalf,
|
||||||
|
words: []
|
||||||
|
};
|
||||||
|
source.splice(index + 1, 0, newSegment);
|
||||||
|
|
||||||
|
$currentTranscription = { ...$currentTranscription };
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text changes only save after 6 keystrokes
|
||||||
|
let keystrokes = 0;
|
||||||
|
function handleKeystrokes() {
|
||||||
|
keystrokes++;
|
||||||
|
if (keystrokes > 6) {
|
||||||
|
handleHistory();
|
||||||
|
keystrokes = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save history on editing
|
||||||
|
function handleHistory() {
|
||||||
|
let currentT = JSON.parse(JSON.stringify($currentTranscription));
|
||||||
|
editorHistory.update((value) => {
|
||||||
|
return [...value, currentT];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertSegmentAbove(index, callback) {
|
||||||
|
const source =
|
||||||
|
translationIndex == -1
|
||||||
|
? $currentTranscription.result.segments
|
||||||
|
: $currentTranscription.translations[translationIndex].result.segments;
|
||||||
|
source.splice(index, 0, {
|
||||||
|
id: JSON.stringify(Date.now()),
|
||||||
|
start: 0,
|
||||||
|
end: 0,
|
||||||
|
text: '',
|
||||||
|
words: []
|
||||||
|
});
|
||||||
|
$currentTranscription = { ...$currentTranscription }; // deep copy
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertSegmentBelow(index, callback) {
|
||||||
|
const source =
|
||||||
|
translationIndex == -1
|
||||||
|
? $currentTranscription.result.segments
|
||||||
|
: $currentTranscription.translations[translationIndex].result.segments;
|
||||||
|
source.splice(index + 1, 0, {
|
||||||
|
id: JSON.stringify(Date.now()),
|
||||||
|
start: 0,
|
||||||
|
end: 0,
|
||||||
|
text: '',
|
||||||
|
words: []
|
||||||
|
});
|
||||||
|
$currentTranscription = { ...$currentTranscription }; // deep copy
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
|
||||||
|
$: if (segment.start <= $currentVideoPlayerTime && $currentVideoPlayerTime <= segment.end) {
|
||||||
|
isActive = true;
|
||||||
|
} else {
|
||||||
|
isActive = false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<tr class:bg-warning={isActive} class:bg-opacity-30={isActive} data-start={segment.start}>
|
||||||
|
<th>{index}</th>
|
||||||
|
<td class="space-x-2">
|
||||||
|
<!-- Start input -->
|
||||||
|
<input
|
||||||
|
class="w-20 input input-sm input-bordered"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
bind:value={segment.start}
|
||||||
|
on:input={(e) => ($currentVideoPlayerTime.set(e.target.value))}
|
||||||
|
on:input={handleHistory}
|
||||||
|
on:click={(e) => {
|
||||||
|
if ($editorSettings.seekOnClick) $currentVideoPlayerTime = e.target.value;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span class="tooltip" data-tip="Set to current time">
|
||||||
|
<button
|
||||||
|
on:click={() => {
|
||||||
|
segment.start = $currentVideoPlayerTime;
|
||||||
|
handleHistory();
|
||||||
|
}}
|
||||||
|
class="btn btn-xs btn-primary"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="w-4 h-4 stroke-white"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path d="M12 7v5l2 2" />
|
||||||
|
<path d="M17 22l5 -3l-5 -3z" />
|
||||||
|
<path d="M13.017 20.943a9 9 0 1 1 7.831 -7.292" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="space-x-2">
|
||||||
|
<!-- End input -->
|
||||||
|
<input
|
||||||
|
class="w-20 input input-sm input-bordered"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
bind:value={segment.end}
|
||||||
|
on:input={(e) => ($currentVideoPlayerTime = e.target.value)}
|
||||||
|
on:input={handleHistory}
|
||||||
|
on:click={(e) => {
|
||||||
|
if ($editorSettings.seekOnClick) $currentVideoPlayerTime = e.target.value;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span class="tooltip" data-tip="Set to current time">
|
||||||
|
<button
|
||||||
|
on:click={() => {
|
||||||
|
segment.end = $currentVideoPlayerTime;
|
||||||
|
handleHistory();
|
||||||
|
}}
|
||||||
|
class="btn btn-xs btn-primary"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="w-4 h-4 stroke-white"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path d="M12 7v5l2 2" />
|
||||||
|
<path d="M17 22l5 -3l-5 -3z" />
|
||||||
|
<path d="M13.017 20.943a9 9 0 1 1 7.831 -7.292" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<!-- Text input -->
|
||||||
|
<div
|
||||||
|
bind:textContent={segment.text}
|
||||||
|
on:input={handleKeystrokes}
|
||||||
|
class="border-2 font-mono font-bold rounded-lg p-3 max-w-md bg-base-100"
|
||||||
|
class:border-error={getCps(segment) > 16}
|
||||||
|
contenteditable="true"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div>
|
||||||
|
<span class="flex flex-col text-xs flex-grow">
|
||||||
|
<span class:text-error={getCps(segment) > 16}>
|
||||||
|
<span class="whitespace-nowrap font-mono font-bold">
|
||||||
|
CPS: {getCps(segment)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<span class="whitespace-nowrap font-mono font-bold">
|
||||||
|
Duration: {Math.round((segment.end - segment.start) * 100) / 100}s
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
class="space-x-1 flex flex-col items-center justify-center space-y-2 md:space-y-0 align-middle lg:flex-row"
|
||||||
|
>
|
||||||
|
<!-- Add above -->
|
||||||
|
<span class="tooltip" data-tip="Insert Above">
|
||||||
|
<button
|
||||||
|
on:click={() => insertSegmentAbove(index, handleHistory)}
|
||||||
|
class="btn btn-primary btn-xs md:btn-sm btn-square"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="w-5 h-5"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path
|
||||||
|
d="M20 6v4a1 1 0 0 1 -1 1h-14a1 1 0 0 1 -1 -1v-4a1 1 0 0 1 1 -1h14a1 1 0 0 1 1 1z"
|
||||||
|
/>
|
||||||
|
<path d="M12 15l0 4" />
|
||||||
|
<path d="M14 17l-4 0" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<!-- Add below -->
|
||||||
|
<span class="tooltip" data-tip="Insert Below">
|
||||||
|
<button
|
||||||
|
on:click={() => insertSegmentBelow(index, handleHistory)}
|
||||||
|
class="btn btn-primary btn-xs md:btn-sm btn-square"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="w-5 h-5"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path
|
||||||
|
d="M4 18v-4a1 1 0 0 1 1 -1h14a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-14a1 1 0 0 1 -1 -1z"
|
||||||
|
/>
|
||||||
|
<path d="M12 9v-4" />
|
||||||
|
<path d="M10 7l4 0" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<!-- Split -->
|
||||||
|
<span class="tooltip" data-tip="Split segment">
|
||||||
|
<button
|
||||||
|
on:click={() => splitSegment(index, handleHistory)}
|
||||||
|
class="btn btn-primary btn-xs md:btn-sm btn-square"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="icon icon-tabler icon-tabler-arrows-split"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path d="M21 17h-8l-3.5 -5h-6.5" />
|
||||||
|
<path d="M21 7h-8l-3.495 5" />
|
||||||
|
<path d="M18 10l3 -3l-3 -3" />
|
||||||
|
<path d="M18 20l3 -3l-3 -3" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<!-- Delete -->
|
||||||
|
<button
|
||||||
|
on:click={deleteSegment(index, handleHistory)}
|
||||||
|
class="btn btn-error btn-xs md:btn-sm btn-square"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="w-5 h-5"
|
||||||
|
width="24"
|
||||||
|
height="24"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke="currentColor"
|
||||||
|
fill="none"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
>
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||||
|
<path
|
||||||
|
d="M20 6a1 1 0 0 1 .117 1.993l-.117 .007h-.081l-.919 11a3 3 0 0 1 -2.824 2.995l-.176 .005h-8c-1.598 0 -2.904 -1.249 -2.992 -2.75l-.005 -.167l-.923 -11.083h-.08a1 1 0 0 1 -.117 -1.993l.117 -.007h16zm-9.489 5.14a1 1 0 0 0 -1.218 1.567l1.292 1.293l-1.292 1.293l-.083 .094a1 1 0 0 0 1.497 1.32l1.293 -1.292l1.293 1.292l.094 .083a1 1 0 0 0 1.32 -1.497l-1.292 -1.293l1.292 -1.293l.083 -.094a1 1 0 0 0 -1.497 -1.32l-1.293 1.292l-1.293 -1.292l-.094 -.083z"
|
||||||
|
stroke-width="0"
|
||||||
|
fill="currentColor"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M14 2a2 2 0 0 1 2 2a1 1 0 0 1 -1.993 .117l-.007 -.117h-4l-.007 .117a1 1 0 0 1 -1.993 -.117a2 2 0 0 1 1.85 -1.995l.15 -.005h4z"
|
||||||
|
stroke-width="0"
|
||||||
|
fill="currentColor"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
22
frontend/src/lib/components/EditorSettings.svelte
Normal file
22
frontend/src/lib/components/EditorSettings.svelte
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script>
|
||||||
|
import { editorSettings } from '$lib/stores';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex flex-row items-center justify-center p-3 space-x-4 m-2">
|
||||||
|
<div
|
||||||
|
class="form-control tooltip"
|
||||||
|
data-tip="When clicking a timestamp input, seek the video to that position."
|
||||||
|
>
|
||||||
|
<label class="label cursor-pointer space-x-2">
|
||||||
|
<span class="label-text">Seek on click</span>
|
||||||
|
<input bind:checked={$editorSettings.seekOnClick} type="checkbox" class="checkbox checkbox-sm" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-control tooltip" data-tip="Automatically save changes every 30s.">
|
||||||
|
<label class="label cursor-pointer space-x-2">
|
||||||
|
<span class="label-text">Autosave</span>
|
||||||
|
<input bind:checked={$editorSettings.autoSave} type="checkbox" class="checkbox checkbox-sm" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
16
frontend/src/lib/components/ErrorTranscription.svelte
Normal file
16
frontend/src/lib/components/ErrorTranscription.svelte
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<script>
|
||||||
|
import {deleteTranscription} from "$lib/utils.js";
|
||||||
|
export let tr;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
<div class="alert alert-error p-3">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
|
||||||
|
<span>
|
||||||
|
<p class="font-bold text-info-content text-md">id-{tr.id}</p>
|
||||||
|
<p class="font-mono text-info-content text-sm opacity-70">Failed: Could not transcribe.</p>
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<button on:click={deleteTranscription(tr.id)} class="btn btn-sm">Delete</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
161
frontend/src/lib/components/ModalDownloadOptions.svelte
Normal file
161
frontend/src/lib/components/ModalDownloadOptions.svelte
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
<script>
|
||||||
|
import {downloadSRT, downloadTXT, downloadJSON, downloadVTT, CLIENT_API_HOST} from '$lib/utils';
|
||||||
|
import toast from 'svelte-french-toast';
|
||||||
|
export let tr;
|
||||||
|
|
||||||
|
let subtitleFormat = "srt";
|
||||||
|
let language = "original";
|
||||||
|
|
||||||
|
function downloadSubtitle() {
|
||||||
|
console.log("download subtitle");
|
||||||
|
let segments = [];
|
||||||
|
let text = "";
|
||||||
|
|
||||||
|
console.log(language)
|
||||||
|
if (language == "original") {
|
||||||
|
segments = tr.result.segments;
|
||||||
|
text = tr.result.text;
|
||||||
|
} else {
|
||||||
|
for (const translation of tr.translations) {
|
||||||
|
if (translation.targetLanguage == language) {
|
||||||
|
segments = translation.result.segments;
|
||||||
|
text = translation.result.text;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (segments.length == 0 || text == "") {
|
||||||
|
toast.error("No data available for download");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subtitleFormat == "srt") {
|
||||||
|
downloadSRT(segments);
|
||||||
|
} else if (subtitleFormat == "vtt") {
|
||||||
|
downloadVTT(segments);
|
||||||
|
} else if (subtitleFormat == "json") {
|
||||||
|
downloadJSON(tr.result);
|
||||||
|
} else if (subtitleFormat == "txt") {
|
||||||
|
downloadTXT(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadMedia() {
|
||||||
|
let link = document.createElement('a');
|
||||||
|
link.href = `${CLIENT_API_HOST}/api/video/${tr.fileName}`;
|
||||||
|
link.target = "_blank";
|
||||||
|
link.download = tr.fileName.split('_WHSHPR_')[1]+".mp4";
|
||||||
|
link.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyText() {
|
||||||
|
console.log("copy text");
|
||||||
|
let text = "";
|
||||||
|
if (language == "original") {
|
||||||
|
text = tr.result.text;
|
||||||
|
} else {
|
||||||
|
for (const translation of tr.translations) {
|
||||||
|
console.log(translation.targetLanguage == language)
|
||||||
|
if (translation.targetLanguage == language) {
|
||||||
|
text = translation.result.text;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Copy tr.result.text to clipboard
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
console.log('Text copied to clipboard');
|
||||||
|
toast.success('Text copied to clipboard');
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error in copying text: ', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog id="modalDownloadOptions" class="modal">
|
||||||
|
<form method="dialog" class="modal-box flex flex-col items-center justify-center">
|
||||||
|
<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
|
||||||
|
{#if tr}
|
||||||
|
<h1 class="text-center font-bold mt-2 pb-2">Download Options</h1>
|
||||||
|
|
||||||
|
<div class="flex flex-row space-x-4">
|
||||||
|
<div class="form-control">
|
||||||
|
<label for="format" class="label">
|
||||||
|
<span class="label-text font-bold">File Format</span>
|
||||||
|
</label>
|
||||||
|
<select bind:value={subtitleFormat} name="format" class="select select-bordered w-full max-w-xs">
|
||||||
|
<option value="srt">SRT</option>
|
||||||
|
<option value="vtt">VTT</option>
|
||||||
|
<option value="json">JSON</option>
|
||||||
|
<option value="txt">TXT</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-control">
|
||||||
|
<label for="language" class="label">
|
||||||
|
<span class="label-text font-bold">Text Language</span>
|
||||||
|
</label>
|
||||||
|
<select bind:value={language} name="language" class="select select-bordered w-full max-w-xs uppercase">
|
||||||
|
<option value="original">✅ {tr.result.language}</option>
|
||||||
|
{#each tr.translations as translation}
|
||||||
|
<option value="{translation.targetLanguage}">🤖 {translation.targetLanguage}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-x-2 mt-8">
|
||||||
|
<span class="tooltip" data-tip="Download {subtitleFormat} file in {language}.">
|
||||||
|
<button on:click={downloadSubtitle} class="btn btn-sm btn-success">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-download" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"></path>
|
||||||
|
<path d="M7 11l5 5l5 -5"></path>
|
||||||
|
<path d="M12 4l0 12"></path>
|
||||||
|
</svg>
|
||||||
|
<span>
|
||||||
|
File
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<span class="tooltip" data-tip="Copy raw text in '{language}' language.">
|
||||||
|
<button on:click={copyText} class="btn btn-sm btn-info">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-copy" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M8 8m0 2a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2z"></path>
|
||||||
|
<path d="M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"></path>
|
||||||
|
</svg>
|
||||||
|
<span>
|
||||||
|
Copy
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<span class="tooltip" data-tip="Download source media">
|
||||||
|
<button on:click={downloadMedia} class="btn btn-sm btn-error">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-download" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M14 3v4a1 1 0 0 0 1 1h4"></path>
|
||||||
|
<path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path>
|
||||||
|
<path d="M12 17v-6"></path>
|
||||||
|
<path d="M9.5 14.5l2.5 2.5l2.5 -2.5"></path>
|
||||||
|
</svg>
|
||||||
|
<span>
|
||||||
|
Media
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="flex items-center justify-center w-screen h-screen">
|
||||||
|
<h1>
|
||||||
|
<span class="loading loading-bars loading-lg" />
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</form>
|
||||||
|
<form method="dialog" class="modal-backdrop">
|
||||||
|
<button>close</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
183
frontend/src/lib/components/ModalTranscriptionForm.svelte
Normal file
183
frontend/src/lib/components/ModalTranscriptionForm.svelte
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
<script>
|
||||||
|
import { validateURL, CLIENT_API_HOST } from '$lib/utils.js';
|
||||||
|
|
||||||
|
import toast from 'svelte-french-toast';
|
||||||
|
|
||||||
|
let errorMessage = '';
|
||||||
|
let disableSubmit = true;
|
||||||
|
let modelSize = 'small';
|
||||||
|
let language = 'auto';
|
||||||
|
let sourceUrl = '';
|
||||||
|
let fileInput;
|
||||||
|
|
||||||
|
let languages = [
|
||||||
|
'auto',
|
||||||
|
'ar',
|
||||||
|
'be',
|
||||||
|
'bg',
|
||||||
|
'bn',
|
||||||
|
'ca',
|
||||||
|
'cs',
|
||||||
|
'cy',
|
||||||
|
'da',
|
||||||
|
'de',
|
||||||
|
'el',
|
||||||
|
'en',
|
||||||
|
'es',
|
||||||
|
'fr',
|
||||||
|
'it',
|
||||||
|
'jp',
|
||||||
|
'nl',
|
||||||
|
'pl',
|
||||||
|
'pt',
|
||||||
|
'ru',
|
||||||
|
'sk',
|
||||||
|
'sl',
|
||||||
|
'sv',
|
||||||
|
'tk',
|
||||||
|
'tr',
|
||||||
|
'zh'
|
||||||
|
];
|
||||||
|
let models = [
|
||||||
|
'tiny',
|
||||||
|
'tiny.en',
|
||||||
|
'base',
|
||||||
|
'base.en',
|
||||||
|
'small',
|
||||||
|
'small.en',
|
||||||
|
'medium',
|
||||||
|
'medium.en',
|
||||||
|
'large-v2'
|
||||||
|
];
|
||||||
|
// Sort the languages
|
||||||
|
languages.sort((a, b) => {
|
||||||
|
if (a == 'auto') return -1;
|
||||||
|
if (b == 'auto') return 1;
|
||||||
|
return a.localeCompare(b);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Function that sends the data as a form to the backend
|
||||||
|
async function sendForm() {
|
||||||
|
if (sourceUrl && !validateURL(sourceUrl)) {
|
||||||
|
toast.error('You must enter a valid URL.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sourceUrl && !fileInput) {
|
||||||
|
toast.error('No file or URL.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let formData = new FormData();
|
||||||
|
formData.append('language', language);
|
||||||
|
formData.append('modelSize', modelSize);
|
||||||
|
formData.append('sourceUrl', sourceUrl);
|
||||||
|
if (sourceUrl == '') {
|
||||||
|
formData.append('file', fileInput.files[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${CLIENT_API_HOST}/api/transcriptions`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set file and sourceUrl to empty
|
||||||
|
sourceUrl = '';
|
||||||
|
fileInput.value = '';
|
||||||
|
|
||||||
|
toast.success('Success!');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reactive statement
|
||||||
|
$: if (sourceUrl && !validateURL(sourceUrl)) {
|
||||||
|
errorMessage = 'Enter a valid URL';
|
||||||
|
disableSubmit = true;
|
||||||
|
} else {
|
||||||
|
errorMessage = '';
|
||||||
|
disableSubmit = false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog id="modalNewTranscription" class="modal">
|
||||||
|
<form method="dialog" class="modal-box">
|
||||||
|
<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
|
||||||
|
{#if errorMessage != ''}
|
||||||
|
<div class="alert alert-error">
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="stroke-current shrink-0 h-6 w-6"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
><path
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||||
|
/></svg
|
||||||
|
>
|
||||||
|
<span>{errorMessage}</span>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="space-y-2 mt-0">
|
||||||
|
<div class="form-control w-full max-w-xs">
|
||||||
|
<label for="file" class="label">
|
||||||
|
<span class="label-text">Pick a file</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
name="file"
|
||||||
|
bind:this={fileInput}
|
||||||
|
type="file"
|
||||||
|
class="file-input file-input-sm file-input-bordered file-input-primary w-full max-w-xs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-control w-full max-w-xs">
|
||||||
|
<label for="sourceUrl" class="label">
|
||||||
|
<span class="label-text">Or a source URL</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
name="sourceUrl"
|
||||||
|
bind:value={sourceUrl}
|
||||||
|
type="text"
|
||||||
|
placeholder="https://youtube.com/watch?v=Hd33fCdW"
|
||||||
|
class="input input-sm input-bordered input-primary w-full max-w-xs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divider mb-0" />
|
||||||
|
<!-- Whisper Configuration -->
|
||||||
|
<div class="flex space-x-4">
|
||||||
|
<div class="form-control w-full max-w-xs">
|
||||||
|
<label for="modelSize" class="label">
|
||||||
|
<span class="label-text">Whisper model</span>
|
||||||
|
</label>
|
||||||
|
<select name="modelSize" bind:value={modelSize} class="select select-bordered">
|
||||||
|
{#each models as m}
|
||||||
|
<option value={m}>{m}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-control w-full max-w-xs">
|
||||||
|
<label for="language" class="label">
|
||||||
|
<span class="label-text">Language</span>
|
||||||
|
</label>
|
||||||
|
<select name="language" bind:value={language} class="select select-bordered">
|
||||||
|
{#each languages as l}
|
||||||
|
<option value={l}>{l}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divider mb-0" />
|
||||||
|
<!--Actions-->
|
||||||
|
<button class="btn btn-wide btn-primary" on:click={sendForm} disabled={disableSubmit}
|
||||||
|
>Start</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form method="dialog" class="modal-backdrop">
|
||||||
|
<button>close</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
85
frontend/src/lib/components/ModalTranslationForm.svelte
Normal file
85
frontend/src/lib/components/ModalTranslationForm.svelte
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import toast from 'svelte-french-toast';
|
||||||
|
import { CLIENT_API_HOST } from '$lib/utils';
|
||||||
|
import { PUBLIC_TRANSLATION_API_HOST } from '$env/static/public';
|
||||||
|
export let tr;
|
||||||
|
|
||||||
|
let targetLanguage = null;
|
||||||
|
|
||||||
|
let availableLanguages = [];
|
||||||
|
const getAvailableLangs = () => {
|
||||||
|
const fetchLanguages = () => {
|
||||||
|
fetch(`${PUBLIC_TRANSLATION_API_HOST}/languages`)
|
||||||
|
.then(res => res.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data) {
|
||||||
|
availableLanguages = data;
|
||||||
|
console.log(availableLanguages)
|
||||||
|
// Languages fetched successfully, stop trying
|
||||||
|
clearInterval(fetchLanguagesInterval);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fetch languages repeatedly until successful
|
||||||
|
const fetchLanguagesInterval = setInterval(fetchLanguages, 5000);
|
||||||
|
fetchLanguages();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTranslate = (id) => {
|
||||||
|
if(targetLanguage) {
|
||||||
|
const url = `${CLIENT_API_HOST}/api/translate/${id}/${targetLanguage}`;
|
||||||
|
fetch(url)
|
||||||
|
.then(() => toast.success('Translation started!'))
|
||||||
|
.catch(error => {
|
||||||
|
console.error(error);
|
||||||
|
toast.error('Error translating text!')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
await getAvailableLangs();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog id="modalTranslation" class="modal">
|
||||||
|
<form method="dialog" class="modal-box flex flex-col items-center justify-center">
|
||||||
|
<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
|
||||||
|
{#if tr}
|
||||||
|
<h1 class="text-center font-bold mt-2 pb-2">
|
||||||
|
Translate
|
||||||
|
</h1>
|
||||||
|
<div>
|
||||||
|
<!-- Language picker -->
|
||||||
|
<div class="form-control w-full max-w-xs">
|
||||||
|
<label for="target-lan" class="label">
|
||||||
|
<span class="label-text">Target language</span>
|
||||||
|
</label>
|
||||||
|
<select bind:value={targetLanguage} name="target-lan" class="select select-bordered">
|
||||||
|
<option disabled selected>Pick one</option>
|
||||||
|
<!-- Iterate all available languages -->
|
||||||
|
{#each availableLanguages as lan}
|
||||||
|
<!-- When we find the source language -->
|
||||||
|
{#if lan.code == tr.result.language}
|
||||||
|
<!-- Iterate all possible target languages -->
|
||||||
|
{#each lan.targets as t}
|
||||||
|
{#if t != tr.result.language}
|
||||||
|
<option value="{t}">{t}</option>
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<!-- End language picker-->
|
||||||
|
<button on:click={handleTranslate(tr.id)} class="btn btn-active btn-primary mt-5">Translate</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</form>
|
||||||
|
<form method="dialog" class="modal-backdrop">
|
||||||
|
<button>close</button>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
11
frontend/src/lib/components/PendingTranscription.svelte
Normal file
11
frontend/src/lib/components/PendingTranscription.svelte
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<script>
|
||||||
|
export let tr;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="alert alert-info p-3">
|
||||||
|
<span class="loading loading-ring loading-md"></span>
|
||||||
|
<span>
|
||||||
|
<p class="font-bold text-info-content text-md">{tr.fileName != "" ? tr.fileName.split("_WHSHPR_")[1] : tr.id}</p>
|
||||||
|
<p class="font-mono text-info-content text-sm opacity-60">Waiting for transcription...</p>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
25
frontend/src/lib/components/PendingTranslation.svelte
Normal file
25
frontend/src/lib/components/PendingTranslation.svelte
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<script>
|
||||||
|
export let tr;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="alert alert-info p-3">
|
||||||
|
<span class="loading loading-dots loading-md"></span>
|
||||||
|
<span>
|
||||||
|
<p class="font-bold text-info-content text-md flex items-center justify-center space-x-2">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-language-hiragana" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M4 5h7"></path>
|
||||||
|
<path d="M7 4c0 4.846 0 7 .5 8"></path>
|
||||||
|
<path d="M10 8.5c0 2.286 -2 4.5 -3.5 4.5s-2.5 -1.135 -2.5 -2c0 -2 1 -3 3 -3s5 .57 5 2.857c0 1.524 -.667 2.571 -2 3.143"></path>
|
||||||
|
<path d="M12 20l4 -9l4 9"></path>
|
||||||
|
<path d="M19.1 18h-6.2"></path>
|
||||||
|
</svg>
|
||||||
|
<span>{tr.fileName != "" ? tr.fileName.split("_WHSHPR_")[1] : tr.id}</span>
|
||||||
|
</p>
|
||||||
|
<p class="opacity-60">
|
||||||
|
<span class="font-mono text-info-content text-sm ">
|
||||||
|
Waiting for translation...
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
75
frontend/src/lib/components/SuccessTranscription.svelte
Normal file
75
frontend/src/lib/components/SuccessTranscription.svelte
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
<!-- SuccessTranscription.svelte -->
|
||||||
|
<script>
|
||||||
|
import {createEventDispatcher} from 'svelte';
|
||||||
|
import {deleteTranscription} from "$lib/utils.js";
|
||||||
|
export let tr;
|
||||||
|
|
||||||
|
const dispatch = createEventDispatcher();
|
||||||
|
let download = () => {
|
||||||
|
dispatch('download', tr); // emit a custom event with the transcription as detail
|
||||||
|
}
|
||||||
|
let translate = () => {
|
||||||
|
dispatch('translate', tr); // emit a custom event with the transcription as detail
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="alert alert-success p-3">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
|
||||||
|
<span>
|
||||||
|
<p class="font-bold text-info-content text-md">{tr.fileName.split("_WHSHPR_")[1]}</p>
|
||||||
|
<p class="font-mono text-info-content text-sm opacity-60 flex space-x-2 md:space-x-4 lg:space-x-8">
|
||||||
|
<span class="space-x-1">
|
||||||
|
<span class="font-bold text-xs">~{Math.round(tr.result.duration)}s long</span>
|
||||||
|
</span>
|
||||||
|
<span class="space-x-1">
|
||||||
|
<span class="font-bold text-xs">{tr.translations.length} translations</span>
|
||||||
|
</span>
|
||||||
|
<span class="space-x-1">
|
||||||
|
<span class="font-bold text-xs">{tr.result.text.split(" ").length} words</span>
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</span>
|
||||||
|
<div class="flex items-center justify-center flex-wrap space-x-2">
|
||||||
|
<a href="/editor/{tr.id}" class="btn btn-xs md:btn-sm">
|
||||||
|
<span class="tooltip flex items-center justify-center" data-tip="Edit">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M12 15l8.385 -8.415a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3z"></path>
|
||||||
|
<path d="M16 5l3 3"></path>
|
||||||
|
<path d="M9 7.07a7 7 0 0 0 1 13.93a7 7 0 0 0 6.929 -6"></path>
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
|
<button on:click={download} onclick="modalDownloadOptions.showModal()" class="btn btn-xs md:btn-sm">
|
||||||
|
<span class="tooltip flex items-center justify-center" data-tip="Download">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"></path>
|
||||||
|
<path d="M7 11l5 5l5 -5"></path>
|
||||||
|
<path d="M12 4l0 12"></path>
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button on:click={translate} class="btn btn-xs md:btn-sm btn-primary">
|
||||||
|
<span class="tooltip flex items-center justify-center" data-tip="Translate">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M4 5h7"></path>
|
||||||
|
<path d="M7 4c0 4.846 0 7 .5 8"></path>
|
||||||
|
<path d="M10 8.5c0 2.286 -2 4.5 -3.5 4.5s-2.5 -1.135 -2.5 -2c0 -2 1 -3 3 -3s5 .57 5 2.857c0 1.524 -.667 2.571 -2 3.143"></path>
|
||||||
|
<path d="M12 20l4 -9l4 9"></path>
|
||||||
|
<path d="M19.1 18h-6.2"></path>
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button on:click={deleteTranscription(tr.id)} class="btn btn-xs md:btn-sm btn-error">
|
||||||
|
<span class="tooltip flex items-center justify-center" data-tip="Delete">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||||
|
<path d="M20 6a1 1 0 0 1 .117 1.993l-.117 .007h-.081l-.919 11a3 3 0 0 1 -2.824 2.995l-.176 .005h-8c-1.598 0 -2.904 -1.249 -2.992 -2.75l-.005 -.167l-.923 -11.083h-.08a1 1 0 0 1 -.117 -1.993l.117 -.007h16zm-9.489 5.14a1 1 0 0 0 -1.218 1.567l1.292 1.293l-1.292 1.293l-.083 .094a1 1 0 0 0 1.497 1.32l1.293 -1.292l1.293 1.292l.094 .083a1 1 0 0 0 1.32 -1.497l-1.292 -1.293l1.292 -1.293l.083 -.094a1 1 0 0 0 -1.497 -1.32l-1.293 1.292l-1.293 -1.292l-.094 -.083z" stroke-width="0" fill="currentColor"></path>
|
||||||
|
<path d="M14 2a2 2 0 0 1 2 2a1 1 0 0 1 -1.993 .117l-.007 -.117h-4l-.007 .117a1 1 0 0 1 -1.993 -.117a2 2 0 0 1 1.85 -1.995l.15 -.005h4z" stroke-width="0" fill="currentColor"></path>
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
1
frontend/src/lib/index.js
Normal file
1
frontend/src/lib/index.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
// place files you want to import through the `$lib` alias in this folder.
|
||||||
25
frontend/src/lib/stores.js
Normal file
25
frontend/src/lib/stores.js
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
|
// contains all transcriptions
|
||||||
|
export const transcriptions = writable([]);
|
||||||
|
|
||||||
|
// contains the current editing transcription
|
||||||
|
export const currentTranscription = writable();
|
||||||
|
|
||||||
|
// transcription to be downloaded
|
||||||
|
export const downloadTranscription = writable(null);
|
||||||
|
|
||||||
|
// Editor history
|
||||||
|
|
||||||
|
export const editorHistory = writable([]);
|
||||||
|
|
||||||
|
// editor settings
|
||||||
|
export let editorSettings = writable({
|
||||||
|
autosave: false,
|
||||||
|
autosaveInterval: 30000,
|
||||||
|
autosaveNotify: true,
|
||||||
|
seekOnClick: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Video player settings
|
||||||
|
export const currentVideoPlayerTime = writable(0);
|
||||||
30
frontend/src/lib/types.ts
Normal file
30
frontend/src/lib/types.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
export type Transcription = {
|
||||||
|
language: string;
|
||||||
|
duration: number;
|
||||||
|
segments: Segment[];
|
||||||
|
id: string;
|
||||||
|
translations: Translation[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Segment = {
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
text: string;
|
||||||
|
score: number;
|
||||||
|
uuid: string;
|
||||||
|
words?: WordData[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type WordData = {
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
text: string;
|
||||||
|
score: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Translation = {
|
||||||
|
sourceLanguage: string;
|
||||||
|
targetLanguage: string;
|
||||||
|
text: string;
|
||||||
|
segments: Segment[];
|
||||||
|
};
|
||||||
120
frontend/src/lib/utils.js
Normal file
120
frontend/src/lib/utils.js
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
import {transcriptions} from './stores';
|
||||||
|
import { PUBLIC_API_HOST } from '$env/static/public';
|
||||||
|
import { dev } from '$app/environment';
|
||||||
|
|
||||||
|
export const CLIENT_API_HOST = `${dev ? PUBLIC_API_HOST : ""}`;
|
||||||
|
export const CLIENT_WS_HOST = `${dev ? PUBLIC_API_HOST.replace("http://", "").replace("https://", "") : ""}`;
|
||||||
|
|
||||||
|
// URL Validator
|
||||||
|
export const validateURL = function (url) {
|
||||||
|
try {
|
||||||
|
new URL(url);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const deleteTranscription = async function (id) {
|
||||||
|
const res = await fetch(`${CLIENT_API_HOST}/api/transcriptions/${id}`, {
|
||||||
|
method: "DELETE"
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
transcriptions.update((_transcriptions) => _transcriptions.filter(t => t.id !== id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getRandomSentence = function () {
|
||||||
|
const sentences = [
|
||||||
|
"Audio in, text out. What's your sound about?",
|
||||||
|
"Drop the beat, I'll drop the text!",
|
||||||
|
"Everybody knows the bird is the word!",
|
||||||
|
"From soundcheck to spellcheck!",
|
||||||
|
"I got 99 problems but transcribing ain't one!",
|
||||||
|
"I'm all ears!",
|
||||||
|
"iTranscribe, you dictate!",
|
||||||
|
"Lost for words?",
|
||||||
|
"Sound check 1, 2, 3...",
|
||||||
|
"Sound's up! What's your script?",
|
||||||
|
"Transcribe, transcribe, transcribe!",
|
||||||
|
"What are you transcribing today?",
|
||||||
|
"What's the story, morning wordy?",
|
||||||
|
"Words, don't come easy, but I can help find the way.",
|
||||||
|
"You speak, I write. It's no magic, just AI!",
|
||||||
|
"Can't understand that language? I can translate!",
|
||||||
|
"I mean every word I say!"
|
||||||
|
]
|
||||||
|
|
||||||
|
const randomSentence = sentences[Math.floor(Math.random() * sentences.length)];
|
||||||
|
|
||||||
|
return randomSentence;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expects a segments array with start, end and text properties
|
||||||
|
export const downloadSRT = function (jsonData) {
|
||||||
|
let srtContent = '';
|
||||||
|
|
||||||
|
jsonData.forEach((segment, index) => {
|
||||||
|
let startSeconds = Math.floor(segment.start);
|
||||||
|
let startMillis = Math.floor((segment.start - startSeconds) * 1000);
|
||||||
|
let start = new Date(startSeconds * 1000 + startMillis).toISOString().substr(11, 12);
|
||||||
|
let endSeconds = Math.floor(segment.end);
|
||||||
|
let endMillis = Math.floor((segment.end - endSeconds) * 1000);
|
||||||
|
let end = new Date(endSeconds * 1000 + endMillis).toISOString().substr(11, 12);
|
||||||
|
|
||||||
|
srtContent += `${index + 1}\n${start} --> ${end}\n${segment.text}\n\n`;
|
||||||
|
});
|
||||||
|
|
||||||
|
let srtBlob = new Blob([srtContent], {type: 'text/plain'});
|
||||||
|
let url = URL.createObjectURL(srtBlob);
|
||||||
|
let link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = 'subtitles.srt';
|
||||||
|
link.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Downloads received text as a TXT file
|
||||||
|
export const downloadTXT = function (text) {
|
||||||
|
let srtBlob = new Blob([text], {type: 'text/plain'});
|
||||||
|
let url = URL.createObjectURL(srtBlob);
|
||||||
|
let link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = 'subtitles.txt';
|
||||||
|
link.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Downloads received JSON data as a JSON file
|
||||||
|
export const downloadJSON = function (jsonData) {
|
||||||
|
let srtBlob = new Blob([JSON.stringify(jsonData)], {type: 'text/plain'});
|
||||||
|
let url = URL.createObjectURL(srtBlob);
|
||||||
|
let link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = 'subtitles.json';
|
||||||
|
link.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expects a segments array with start, end and text properties
|
||||||
|
export const downloadVTT = function (jsonData) {
|
||||||
|
let vttContent = 'WEBVTT\n\n'; // VTT files start with "WEBVTT" line
|
||||||
|
|
||||||
|
jsonData.forEach((segment, index) => {
|
||||||
|
let startSeconds = Math.floor(segment.start);
|
||||||
|
let startMillis = Math.floor((segment.start - startSeconds) * 1000);
|
||||||
|
let start = new Date(startSeconds * 1000 + startMillis).toISOString().substr(11, 12).replace('.', ',');
|
||||||
|
|
||||||
|
let endSeconds = Math.floor(segment.end);
|
||||||
|
let endMillis = Math.floor((segment.end - endSeconds) * 1000);
|
||||||
|
let end = new Date(endSeconds * 1000 + endMillis).toISOString().substr(11, 12).replace('.', ',');
|
||||||
|
|
||||||
|
vttContent += `${index + 1}\n${start} --> ${end}\n- ${segment.text}\n\n`;
|
||||||
|
});
|
||||||
|
|
||||||
|
let vttBlob = new Blob([vttContent], {type: 'text/plain'});
|
||||||
|
let url = URL.createObjectURL(vttBlob);
|
||||||
|
let link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = 'subtitles.vtt';
|
||||||
|
link.click();
|
||||||
|
}
|
||||||
|
|
||||||
20
frontend/src/routes/+layout.js
Normal file
20
frontend/src/routes/+layout.js
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { transcriptions } from '$lib/stores';
|
||||||
|
import { browser, dev } from '$app/environment';
|
||||||
|
import { PUBLIC_INTERNAL_API_HOST } from '$env/static/public';
|
||||||
|
import { CLIENT_API_HOST } from '$lib/utils';
|
||||||
|
|
||||||
|
/** @type {import('./$types').PageLoad} */
|
||||||
|
export async function load({ fetch }) {
|
||||||
|
// Use different endpoints for server-side and client-side
|
||||||
|
const endpoint = browser ? `${CLIENT_API_HOST}/api/transcriptions` : `${PUBLIC_INTERNAL_API_HOST}/api/transcriptions`;
|
||||||
|
console.log(endpoint);
|
||||||
|
|
||||||
|
const response = await fetch(endpoint);
|
||||||
|
const ts = await response.json();
|
||||||
|
|
||||||
|
if (ts) {
|
||||||
|
transcriptions.update(_ => ts.length > 0 ? ts : []);
|
||||||
|
} else {
|
||||||
|
transcriptions.update(_ => []);
|
||||||
|
}
|
||||||
|
}
|
||||||
5
frontend/src/routes/+layout.svelte
Normal file
5
frontend/src/routes/+layout.svelte
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<script>
|
||||||
|
import "../app.css";
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<slot />
|
||||||
11
frontend/src/routes/+page.js
Normal file
11
frontend/src/routes/+page.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
/** @type {import('./$types').PageLoad} */
|
||||||
|
import {getRandomSentence} from "$lib/utils";
|
||||||
|
|
||||||
|
|
||||||
|
export async function load() {
|
||||||
|
const randomSentence = getRandomSentence();
|
||||||
|
|
||||||
|
return {
|
||||||
|
randomSentence: randomSentence
|
||||||
|
};
|
||||||
|
};
|
||||||
126
frontend/src/routes/+page.svelte
Normal file
126
frontend/src/routes/+page.svelte
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
<script>
|
||||||
|
import { Toaster } from 'svelte-french-toast';
|
||||||
|
import { transcriptions } from '$lib/stores';
|
||||||
|
import { browser, dev } from '$app/environment';
|
||||||
|
import { CLIENT_WS_HOST } from '$lib/utils';
|
||||||
|
import { onMount, onDestroy } from 'svelte';
|
||||||
|
import ModalTranscriptionForm from '$lib/components/ModalTranscriptionForm.svelte';
|
||||||
|
import ModalDownloadOptions from '$lib/components/ModalDownloadOptions.svelte';
|
||||||
|
import ModalTranslationForm from '$lib/components/ModalTranslationForm.svelte';
|
||||||
|
import SuccessTranscription from '$lib/components/SuccessTranscription.svelte';
|
||||||
|
import PendingTranscription from '$lib/components/PendingTranscription.svelte';
|
||||||
|
import PendingTranslation from '$lib/components/PendingTranslation.svelte';
|
||||||
|
import ErrorTranscription from '$lib/components/ErrorTranscription.svelte';
|
||||||
|
|
||||||
|
//export let data;
|
||||||
|
let socket;
|
||||||
|
export let data;
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
if (!browser) {
|
||||||
|
console.log('Server, not connecting');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let new_uri = '';
|
||||||
|
var loc = window.location;
|
||||||
|
if (loc.protocol === 'https:') {
|
||||||
|
new_uri = 'wss:';
|
||||||
|
} else {
|
||||||
|
new_uri = 'ws:';
|
||||||
|
}
|
||||||
|
new_uri += '//' + (CLIENT_WS_HOST == '' ? loc.host : CLIENT_WS_HOST);
|
||||||
|
new_uri += '/ws/transcriptions';
|
||||||
|
console.log('Connecting to: ', new_uri);
|
||||||
|
socket = new WebSocket(new_uri);
|
||||||
|
|
||||||
|
socket.onopen = () => console.log('WebSocket is connected...');
|
||||||
|
socket.onerror = (error) => console.log('WebSocket Error: ', error);
|
||||||
|
socket.onclose = (event) => {
|
||||||
|
console.log('WebSocket is closed with code: ', event.code, ' and reason: ', event.reason);
|
||||||
|
setTimeout(() => {
|
||||||
|
console.log('Reconnecting...');
|
||||||
|
connect();
|
||||||
|
}, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.onmessage = (event) => {
|
||||||
|
let update = JSON.parse(event.data);
|
||||||
|
// use update to update the store
|
||||||
|
transcriptions.update(transcriptions => {
|
||||||
|
let index = transcriptions.findIndex(tr => tr.id === update.id);
|
||||||
|
if (index >= 0) {
|
||||||
|
// replace the item at index
|
||||||
|
transcriptions[index] = update;
|
||||||
|
} else {
|
||||||
|
// add the new item
|
||||||
|
transcriptions.push(update);
|
||||||
|
}
|
||||||
|
return transcriptions; // return a new object to trigger reactivity
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
connect();
|
||||||
|
});
|
||||||
|
|
||||||
|
let downloadTranscription = null;
|
||||||
|
let handleDownload = (event) => {
|
||||||
|
downloadTranscription = event.detail; // this will be the transcription to download
|
||||||
|
modalDownloadOptions.showModal(); // show the modal
|
||||||
|
};
|
||||||
|
let translateTranscription = null;
|
||||||
|
let handleTranslate = (event) => {
|
||||||
|
translateTranscription = event.detail; // this will be the transcription to translate
|
||||||
|
modalTranslation.showModal(); // show the modal
|
||||||
|
};
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
if (socket) {
|
||||||
|
socket.close(1000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Toaster />
|
||||||
|
<ModalDownloadOptions tr={downloadTranscription} />
|
||||||
|
<ModalTranslationForm tr={translateTranscription} />
|
||||||
|
<ModalTranscriptionForm />
|
||||||
|
|
||||||
|
<header>
|
||||||
|
<h1 class="flex items-center justify-center space-x-4 font-bold text-4xl mt-8">
|
||||||
|
<span>
|
||||||
|
<img class="w-20 h-20" src="/logo.svg" alt="Logo: a cloud whispering" />
|
||||||
|
</span>
|
||||||
|
<span> Whishper </span>
|
||||||
|
</h1>
|
||||||
|
<h2 class="text-md text-center opacity-70 font-mono">{data.randomSentence}</h2>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="card w-4/6 bg-neutral text-neutral-content mx-auto mt-4 mb-8">
|
||||||
|
<button
|
||||||
|
class="btn btn-primary mx-auto max-w-md mt-8 btn-md"
|
||||||
|
onclick="modalNewTranscription.showModal()">✨ new transcription</button
|
||||||
|
>
|
||||||
|
<div class="card-body items-center text-center mb-0">
|
||||||
|
{#if $transcriptions.length > 0}
|
||||||
|
{#each $transcriptions as tr (tr.id)}
|
||||||
|
{#if tr.status == 2}
|
||||||
|
<SuccessTranscription {tr} on:download={handleDownload} on:translate={handleTranslate} />
|
||||||
|
{/if}
|
||||||
|
{#if tr.status < 2 && tr.status >= 0}
|
||||||
|
<PendingTranscription {tr} />
|
||||||
|
{/if}
|
||||||
|
{#if tr.status == 3}
|
||||||
|
<PendingTranslation {tr} />
|
||||||
|
{/if}
|
||||||
|
{#if tr.status < 0}
|
||||||
|
<ErrorTranscription {tr} />
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
{:else}
|
||||||
|
<p class="text-center font-bold text-2xl">🔮 No transcriptions yet 🔮</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
17
frontend/src/routes/editor/[id]/+page.js
Normal file
17
frontend/src/routes/editor/[id]/+page.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
/** @type {import('./$types').PageLoad} */
|
||||||
|
import { currentTranscription } from '$lib/stores';
|
||||||
|
import { PUBLIC_INTERNAL_API_HOST } from '$env/static/public';
|
||||||
|
import { CLIENT_API_HOST } from '$lib/utils';
|
||||||
|
import { browser } from '$app/environment';
|
||||||
|
|
||||||
|
export async function load({params}) {
|
||||||
|
// Fetch json from /api/transcriptions/{id}
|
||||||
|
let id = params.id;
|
||||||
|
// Use different endpoints for server-side and client-side
|
||||||
|
|
||||||
|
const endpoint = browser ? `${CLIENT_API_HOST}/api/transcriptions` : `${PUBLIC_INTERNAL_API_HOST}/api/transcriptions`;
|
||||||
|
const response = await fetch(`${endpoint}/${id}`);
|
||||||
|
const ts = await response.json();
|
||||||
|
// Set currentTranscription to the fetched transcription
|
||||||
|
currentTranscription.set(ts);
|
||||||
|
};
|
||||||
45
frontend/src/routes/editor/[id]/+page.svelte
Normal file
45
frontend/src/routes/editor/[id]/+page.svelte
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
<script>
|
||||||
|
/** @type {import('./$types').PageData} */
|
||||||
|
import toast, { Toaster } from 'svelte-french-toast';
|
||||||
|
import Editor from '$lib/components/Editor.svelte';
|
||||||
|
import {currentVideoPlayerTime, currentTranscription} from '$lib/stores';
|
||||||
|
import { CLIENT_API_HOST } from '$lib/utils';
|
||||||
|
|
||||||
|
|
||||||
|
let video;
|
||||||
|
let tolerance = 0.1; // Tolerance level in seconds
|
||||||
|
let canPlay = false;
|
||||||
|
$: if(canPlay && video && Math.abs(video.currentTime - $currentVideoPlayerTime) > tolerance) {
|
||||||
|
console.log(video.currentTime, $currentVideoPlayerTime)
|
||||||
|
video.currentTime = $currentVideoPlayerTime;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Toaster />
|
||||||
|
{#if $currentTranscription}
|
||||||
|
<div class="grid grid-cols-3 h-screen overflow-hidden">
|
||||||
|
<div class="col-span-1 bg-transparent overflow-hidden">
|
||||||
|
<div class="h-full w-full relative">
|
||||||
|
<video id="video"
|
||||||
|
controls
|
||||||
|
bind:this={video}
|
||||||
|
on:timeupdate={(e) => $currentVideoPlayerTime.set(e.target.currentTime)}
|
||||||
|
on:canplay={() => canPlay = true}
|
||||||
|
on:loadedmetadata={() => canPlay = true}
|
||||||
|
class="absolute top-0 left-0 h-full w-full">
|
||||||
|
<source src="{CLIENT_API_HOST}/api/video/{$currentTranscription.fileName}" type="video/mp4" />
|
||||||
|
<track kind="captions" />
|
||||||
|
</video>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-span-2 bg-content overflow-auto">
|
||||||
|
<Editor />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="flex items-center justify-center w-screen h-screen">
|
||||||
|
<h1>
|
||||||
|
<span class="loading loading-bars loading-lg" />
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
BIN
frontend/static/30sec.webm
Normal file
BIN
frontend/static/30sec.webm
Normal file
Binary file not shown.
BIN
frontend/static/favicon.webp
Normal file
BIN
frontend/static/favicon.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.0 KiB |
19
frontend/static/logo.svg
Normal file
19
frontend/static/logo.svg
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<svg id="emoji" viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<g id="color">
|
||||||
|
<path fill="#d0cfce" stroke="none" d="M14.5968,29.9075c-0.0396,0.4525-0.4062,0.8186-0.8602,0.8673C8.233,31.3643,4,36.7833,4,43.3794 C4,50.3693,8.8475,56.751,14.8272,56.751h41.2775c1.3997-0.037,2.5589-0.1579,3.7218-0.551C63.0257,54.6289,68,49.4069,68,42.6607 c0-7.079-4.8912-12.8736-11.0809-13.3441c-0.4735-0.036-0.8576-0.3674-0.9479-0.8313 c-1.3827-7.1005-7.7614-12.4363-15.3028-12.4363c-4.9012,0-9.2671,2.2189-12.1023,5.7487c-0.277,0.3449-0.742,0.503-1.151,0.3315 c-1.091-0.4575-2.2432-0.6789-3.5324-0.6789C19.0109,21.4502,15.012,25.1682,14.5968,29.9075z"/>
|
||||||
|
</g>
|
||||||
|
<g id="hair"/>
|
||||||
|
<g id="skin"/>
|
||||||
|
<g id="skin-shadow"/>
|
||||||
|
<g id="line">
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M59.4442,55.4591C64.3882,53.8362,68,48.7016,68,42.6183c0-7.079-4.8912-12.8736-11.0809-13.3441 c-0.4735-0.036-0.8576-0.3674-0.9479-0.8313c-1.3827-7.1005-7.7614-12.4363-15.3028-12.4363 c-4.9012,0-9.2671,2.2189-12.1023,5.7487c-0.277,0.3449-0.742,0.503-1.151,0.3315c-1.091-0.4575-2.2432-0.6789-3.5324-0.6789 c-4.8718,0-8.8707,3.718-9.2859,8.4573c-0.0396,0.4525-0.4062,0.8186-0.8602,0.8673C8.233,31.322,4,36.741,4,43.3371 c0,6.9899,4.8475,12.6562,10.8272,12.6562l36.2187,0"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M31.686,32.062 c-1.2083,0.9992-2.7458,1.5119-4.312,1.438c-1.5664,0.0745-3.1043-0.4379-4.313-1.437"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M48.939,32.062 c-1.2083,0.9992-2.7458,1.5119-4.312,1.438c-1.5664,0.0745-3.1043-0.4379-4.313-1.437"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M39.6114,45.3333c1.6569,0,3-1.1379,3-2.5417c0-1.0528-0.7555-1.9561-1.8323-2.3419c-0.3589-0.1286-0.7535-0.1997-1.1677-0.1997"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M39.1843,50.4062c0.9401,0,2.0159-0.5708,2.3309-1.472c0.5041-1.4419-0.3552-3.0541-1.9192-3.6009"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M62.3636,45.5589c2.1545-3.308,2.0114-7.9339-1.9915-9.7984c-1.7893-0.8334-3.8681-0.6097-4.9454,1.0444 c-0.5386,0.827-0.3048,1.9341,0.5222,2.4727"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M46.0899,46.5506c4.7602,2.7667,12.0053,5.3518,16.2737-0.9917"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M55.955,59.826c-0.2166,1.9335-1.9589,3.369-3.8924,3.1524c-1.6258-0.1821-2.8687-1.4434-3.0943-2.9898"/>
|
||||||
|
<path fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="2" d="M46.0899,46.5506c0,0,10.7036,5.7177,9.8651,13.2754"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.1 KiB |
BIN
frontend/static/somevideo.webm
Normal file
BIN
frontend/static/somevideo.webm
Normal file
Binary file not shown.
11
frontend/svelte.config.js
Normal file
11
frontend/svelte.config.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
//import adapter from '@sveltejs/adapter-auto';
|
||||||
|
import adapterNode from '@sveltejs/adapter-node';
|
||||||
|
import { vitePreprocess } from '@sveltejs/kit/vite';
|
||||||
|
/** @type {import('@sveltejs/kit').Config} */
|
||||||
|
const config = {
|
||||||
|
kit: {
|
||||||
|
adapter: adapterNode()
|
||||||
|
},
|
||||||
|
preprocess: vitePreprocess()
|
||||||
|
};
|
||||||
|
export default config;
|
||||||
8
frontend/tailwind.config.js
Normal file
8
frontend/tailwind.config.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
export default {
|
||||||
|
content: ['./src/**/*.{html,js,svelte,ts}'],
|
||||||
|
theme: {
|
||||||
|
extend: {}
|
||||||
|
},
|
||||||
|
plugins: [require("daisyui")],
|
||||||
|
};
|
||||||
6
frontend/vite.config.js
Normal file
6
frontend/vite.config.js
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { sveltekit } from '@sveltejs/kit/vite';
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [sveltekit()]
|
||||||
|
});
|
||||||
1804
frontend/yarn.lock
Normal file
1804
frontend/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
BIN
misc/banner.png
Normal file
BIN
misc/banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 83 KiB |
35
nginx.conf
Normal file
35
nginx.conf
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
gzip on;
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
|
||||||
|
location /api/video {
|
||||||
|
alias /app/uploads/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /languages {
|
||||||
|
proxy_pass http://translate:5000;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api {
|
||||||
|
client_max_body_size 1024M;
|
||||||
|
proxy_pass http://whishper-backend:8080;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /ws {
|
||||||
|
proxy_pass http://whishper-backend:8080;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://whishper-frontend:3000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
33
setup-linux.sh
Normal file
33
setup-linux.sh
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Copy env.example to .env
|
||||||
|
# check if .env exists
|
||||||
|
if [ -f .env ]; then
|
||||||
|
echo ".env file exists"
|
||||||
|
echo "Do you want to overwrite it? (y/n)"
|
||||||
|
read answer
|
||||||
|
if [ "$answer" != "${answer#[Yy]}" ] ;then
|
||||||
|
echo "Copying env.example to .env"
|
||||||
|
cp env.example .env
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo ".env file does not exist"
|
||||||
|
echo "Copying env.example to .env"
|
||||||
|
cp env.example .env
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create necessary directories for libretranslate
|
||||||
|
echo "Creating necessary directories for libretranslate"
|
||||||
|
sudo mkdir -p ./whishper_data/libretranslate/{data,cache} 2&1> /dev/null
|
||||||
|
|
||||||
|
# This permissions are for libretranslate docker container
|
||||||
|
echo "Setting permissions for libretranslate"
|
||||||
|
sudo chown -R 1032:1032 ./whishper_data/libretranslate 2&1> /dev/null
|
||||||
|
|
||||||
|
echo "Do you want to pull and build docker images? (y/n)"
|
||||||
|
read answer
|
||||||
|
if [ "$answer" != "${answer#[Yy]}" ] ;then
|
||||||
|
echo "Pulling and building docker images"
|
||||||
|
docker compose pull
|
||||||
|
docker compose build
|
||||||
|
fi
|
||||||
6
transcription-api/.dockerignore
Normal file
6
transcription-api/.dockerignore
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
.env
|
||||||
|
__pycache__/
|
||||||
|
.ruff_cache
|
||||||
|
.venv
|
||||||
|
.vscode
|
||||||
|
whisper_models/
|
||||||
21
transcription-api/Dockerfile
Normal file
21
transcription-api/Dockerfile
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
FROM python:3.10-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN export DEBIAN_FRONTEND=noninteractive \
|
||||||
|
&& apt-get -qq update \
|
||||||
|
&& apt-get -qq install --no-install-recommends \
|
||||||
|
ffmpeg curl\
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY requirements.txt requirements.txt
|
||||||
|
RUN pip3 install -r requirements.txt
|
||||||
|
RUN pip3 install python-multipart
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s \
|
||||||
|
CMD ["python3", "healthcheck.py"]
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
CMD ["python3", "main.py"]
|
||||||
68
transcription-api/backends/backend.py
Normal file
68
transcription-api/backends/backend.py
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
|
||||||
|
from typing import Any, Mapping, TypedDict
|
||||||
|
import numpy as np
|
||||||
|
from faster_whisper.audio import decode_audio # type: ignore
|
||||||
|
|
||||||
|
SUPPORTED_MODELS = ["tiny", "tiny.en", "small", "small.en", "base", "base.en", "medium", "medium.en", "large-v2"]
|
||||||
|
|
||||||
|
WordData = TypedDict(
|
||||||
|
"WordData", {"word": str, "start": float | str, "end": float | str, "score": float}
|
||||||
|
)
|
||||||
|
|
||||||
|
Segment = TypedDict(
|
||||||
|
"Segment",
|
||||||
|
{
|
||||||
|
"id": str,
|
||||||
|
"text": str,
|
||||||
|
"start": float | str,
|
||||||
|
"end": float | str,
|
||||||
|
"score": float,
|
||||||
|
"words": list[WordData],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
Transcription = TypedDict(
|
||||||
|
"Transcription",
|
||||||
|
{
|
||||||
|
"text": str,
|
||||||
|
"language": str,
|
||||||
|
"duration": float,
|
||||||
|
"segments": list[Segment],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
class Backend:
|
||||||
|
name: str = "faster-whisper"
|
||||||
|
model_size: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if self.model_size not in self.supported_model_sizes():
|
||||||
|
raise ValueError(f"model must be one of {self.supported_model_sizes()}")
|
||||||
|
|
||||||
|
def supported_backends(self):
|
||||||
|
"""
|
||||||
|
This is of not much use as of the moment, If we ever support multiple
|
||||||
|
backends this can be utilized.
|
||||||
|
"""
|
||||||
|
return ["faster-whisper"]
|
||||||
|
|
||||||
|
def model_path(self) -> str:
|
||||||
|
"""
|
||||||
|
Returns the local path to the model, error-out if unavailable
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def supported_model_sizes(self) -> list[str]:
|
||||||
|
return SUPPORTED_MODELS
|
||||||
|
|
||||||
|
def download_model(self):
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def load(self):
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def transcribe(self, input: np.ndarray) -> list[Segment]:
|
||||||
|
"""
|
||||||
|
This should return word level transcription data.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
97
transcription-api/backends/fasterwhisper.py
Normal file
97
transcription-api/backends/fasterwhisper.py
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import numpy as np
|
||||||
|
from .backend import Backend, Transcription, Segment
|
||||||
|
import os, math
|
||||||
|
from tqdm import tqdm # type: ignore
|
||||||
|
import uuid
|
||||||
|
from faster_whisper import WhisperModel, download_model, decode_audio
|
||||||
|
|
||||||
|
class FasterWhisperBackend(Backend):
|
||||||
|
device: str = "cpu" # cpu, cuda
|
||||||
|
quantization: str = "int8" # int8, float16
|
||||||
|
model: WhisperModel | None = None
|
||||||
|
|
||||||
|
def __init__(self, model_size, device: str = "cpu"):
|
||||||
|
self.model_size = model_size
|
||||||
|
self.device = device
|
||||||
|
self.__post_init__()
|
||||||
|
|
||||||
|
def model_path(self) -> str:
|
||||||
|
local_model_path = os.path.join(
|
||||||
|
os.environ["WHISPER_MODELS_DIR"], f"faster-whisper-{self.model_size}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if os.path.exists(local_model_path):
|
||||||
|
return local_model_path
|
||||||
|
else:
|
||||||
|
raise RuntimeError(f"model not found in {local_model_path}")
|
||||||
|
|
||||||
|
def load(self) -> None:
|
||||||
|
self.model = WhisperModel(
|
||||||
|
self.model_path(), device=self.device, compute_type=self.quantization
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_model(self) -> None:
|
||||||
|
print(f"Downloading model {self.model_size}...")
|
||||||
|
local_model_path = os.path.join(os.environ["WHISPER_MODELS_DIR"], f"faster-whisper-{self.model_size}")
|
||||||
|
local_model_cache = os.path.join(os.environ["WHISPER_MODELS_DIR"], f"faster-whisper-{self.model_size}", "cache")
|
||||||
|
# Check if directory exists
|
||||||
|
if not os.path.exists(local_model_path):
|
||||||
|
os.makedirs(local_model_path)
|
||||||
|
try:
|
||||||
|
download_model(self.model_size, output_dir=local_model_path, local_files_only=True, cache_dir=local_model_cache)
|
||||||
|
print("Model already cached...")
|
||||||
|
except:
|
||||||
|
download_model(self.model_size, output_dir=local_model_path, local_files_only=False, cache_dir=local_model_cache)
|
||||||
|
|
||||||
|
def transcribe(
|
||||||
|
self, input: np.ndarray, silent: bool = False, language: str = None
|
||||||
|
) -> Transcription:
|
||||||
|
"""
|
||||||
|
Return word level transcription data.
|
||||||
|
World level probabities are calculated by ctranslate2.models.Whisper.align
|
||||||
|
"""
|
||||||
|
result: list[Segment] = []
|
||||||
|
assert self.model is not None
|
||||||
|
segments, info = self.model.transcribe(
|
||||||
|
input,
|
||||||
|
beam_size=5,
|
||||||
|
word_timestamps=True,
|
||||||
|
language=language,
|
||||||
|
)
|
||||||
|
# ps = playback seconds
|
||||||
|
with tqdm(
|
||||||
|
total=info.duration, unit_scale=True, unit="ps", disable=silent
|
||||||
|
) as pbar:
|
||||||
|
for segment in segments:
|
||||||
|
if segment.words is None:
|
||||||
|
continue
|
||||||
|
id = uuid.uuid4().hex
|
||||||
|
segment_extract: Segment = {
|
||||||
|
"id": id,
|
||||||
|
"text": segment.text,
|
||||||
|
"start": segment.start,
|
||||||
|
"end": segment.end,
|
||||||
|
"score": round(math.exp(segment.avg_logprob), 2),
|
||||||
|
"words": [
|
||||||
|
{
|
||||||
|
"start": w.start,
|
||||||
|
"end": w.end,
|
||||||
|
"word": w.word,
|
||||||
|
"score": round(w.probability, 2),
|
||||||
|
}
|
||||||
|
for w in segment.words
|
||||||
|
],
|
||||||
|
}
|
||||||
|
result.append(segment_extract)
|
||||||
|
if not silent:
|
||||||
|
pbar.update(segment.end - pbar.last_print_n)
|
||||||
|
|
||||||
|
text = " ".join([segment["text"] for segment in result])
|
||||||
|
text = ' '.join(text.strip().split())
|
||||||
|
transcription: Transcription = {
|
||||||
|
"text": text,
|
||||||
|
"language": info.language,
|
||||||
|
"duration": info.duration,
|
||||||
|
"segments": result,
|
||||||
|
}
|
||||||
|
return transcription
|
||||||
11
transcription-api/docker-compose.yml
Normal file
11
transcription-api/docker-compose.yml
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
version: "3"
|
||||||
|
|
||||||
|
services:
|
||||||
|
whisper-api:
|
||||||
|
container_name: whisper-api
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8088:8000"
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
|
||||||
6
transcription-api/healthcheck.py
Normal file
6
transcription-api/healthcheck.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import requests
|
||||||
|
|
||||||
|
response = requests.get(
|
||||||
|
url='http://0.0.0.0:8000/healthcheck/',
|
||||||
|
timeout=60
|
||||||
|
)
|
||||||
43
transcription-api/main.py
Normal file
43
transcription-api/main.py
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
from dotenv import load_dotenv
|
||||||
|
from fastapi import FastAPI, UploadFile, File
|
||||||
|
from models import ModelSize, Languages, DeviceType
|
||||||
|
from transcribe import transcribe_file, transcribe_from_filename
|
||||||
|
import uvicorn
|
||||||
|
import os
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Annotated
|
||||||
|
from backends.fasterwhisper import FasterWhisperBackend
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
@app.post("/transcribe/")
|
||||||
|
async def transcribe_endpoint(file: UploadFile = File(None),
|
||||||
|
filename: str = None,
|
||||||
|
model_size: ModelSize = ModelSize.small,
|
||||||
|
language: Languages = Languages.auto,
|
||||||
|
device: DeviceType = DeviceType.cpu):
|
||||||
|
|
||||||
|
print(f"Transcribing with model {model_size.value} on device {device.value}...")
|
||||||
|
if file is not None:
|
||||||
|
# if a file is uploaded, use it
|
||||||
|
return await transcribe_file(file, model_size.value, language.value, device.value)
|
||||||
|
elif filename is not None:
|
||||||
|
# if a filename is provided, use it
|
||||||
|
return await transcribe_from_filename(filename, model_size.value, language.value, device.value)
|
||||||
|
else:
|
||||||
|
return {"detail": "No file uploaded and no filename provided"}
|
||||||
|
|
||||||
|
@app.get("/healthcheck/")
|
||||||
|
async def healthcheck():
|
||||||
|
return {"status": "healthy"}
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# Get model list (comma separated) from environment variable
|
||||||
|
model_list = os.environ.get("WHISPER_MODELS", "tiny,base,small")
|
||||||
|
model_list = model_list.split(",")
|
||||||
|
for model in model_list:
|
||||||
|
m = FasterWhisperBackend(model_size=model)
|
||||||
|
m.get_model()
|
||||||
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|
||||||
45
transcription-api/models.py
Normal file
45
transcription-api/models.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
from enum import Enum
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
class DeviceType(str, Enum):
|
||||||
|
cpu = "cpu"
|
||||||
|
cuda = "cuda"
|
||||||
|
|
||||||
|
class ModelSize(str, Enum):
|
||||||
|
tiny_en = "tiny.en"
|
||||||
|
tiny = "tiny"
|
||||||
|
base_en = "base.en"
|
||||||
|
base = "base"
|
||||||
|
small_en = "small.en"
|
||||||
|
small = "small"
|
||||||
|
medium_en = "medium.en"
|
||||||
|
medium = "medium"
|
||||||
|
large_v2 = "large-v2"
|
||||||
|
|
||||||
|
class Languages(str, Enum):
|
||||||
|
auto = "auto"
|
||||||
|
ar = "ar"
|
||||||
|
be = "be"
|
||||||
|
bg = "bg"
|
||||||
|
bn = "bn"
|
||||||
|
ca = "ca"
|
||||||
|
cs = "cs"
|
||||||
|
cy = "cy"
|
||||||
|
da = "da"
|
||||||
|
de = "de"
|
||||||
|
el = "el"
|
||||||
|
en = "en"
|
||||||
|
es = "es"
|
||||||
|
fr = "fr"
|
||||||
|
it = "it"
|
||||||
|
jp = "jp"
|
||||||
|
nl = "nl"
|
||||||
|
pl = "pl"
|
||||||
|
pt = "pt"
|
||||||
|
ru = "ru"
|
||||||
|
sk = "sk"
|
||||||
|
sl = "sl"
|
||||||
|
sv = "sv"
|
||||||
|
tk = "tk"
|
||||||
|
tr = "tr"
|
||||||
|
zh = "zh"
|
||||||
6
transcription-api/requirements.txt
Normal file
6
transcription-api/requirements.txt
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
fastapi==0.100.1
|
||||||
|
faster_whisper==0.7.1
|
||||||
|
pydantic==2.1.1
|
||||||
|
python-dotenv==1.0.0
|
||||||
|
uvicorn==0.23.2
|
||||||
|
python-multipart
|
||||||
56
transcription-api/transcribe.py
Normal file
56
transcription-api/transcribe.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
from backends.fasterwhisper import FasterWhisperBackend
|
||||||
|
from backends.backend import Transcription
|
||||||
|
from faster_whisper import decode_audio
|
||||||
|
from models import DeviceType
|
||||||
|
from typing import Optional
|
||||||
|
import numpy as np
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
|
||||||
|
def convert_audio(file) -> np.ndarray:
|
||||||
|
return decode_audio(file, split_stereo=False, sampling_rate=16000)
|
||||||
|
|
||||||
|
async def transcribe_from_filename(filename: str,
|
||||||
|
model_size: int,
|
||||||
|
language: Optional[str] = None,
|
||||||
|
device: DeviceType = DeviceType.cpu) -> Transcription:
|
||||||
|
|
||||||
|
filepath = os.path.join(os.environ["UPLOAD_DIR"], filename)
|
||||||
|
if not os.path.exists(filepath):
|
||||||
|
raise RuntimeError(f"file not found in {filepath}")
|
||||||
|
audio = convert_audio(filepath)
|
||||||
|
return await transcribe_audio(audio, model_size, language, device)
|
||||||
|
|
||||||
|
async def transcribe_file(file: io.BytesIO,
|
||||||
|
model_size: int,
|
||||||
|
language: Optional[str] = None,
|
||||||
|
device: DeviceType = DeviceType.cpu) -> Transcription:
|
||||||
|
contents = await file.read() # async read
|
||||||
|
if len(contents) < 150 * 1024 * 1024: # file is smaller than 150MB
|
||||||
|
audio = convert_audio(io.BytesIO(contents))
|
||||||
|
else:
|
||||||
|
# Save the uploaded file temporarily on disk
|
||||||
|
with open(file.filename, 'wb') as f:
|
||||||
|
f.write(contents)
|
||||||
|
# Check if file exists
|
||||||
|
if not os.path.exists(file.filename):
|
||||||
|
raise RuntimeError(f"file not found in {file.filename}")
|
||||||
|
# Corrected to use the function in this file
|
||||||
|
audio = convert_audio(file.filename)
|
||||||
|
os.remove(file.filename)
|
||||||
|
return await transcribe_audio(audio, model_size, language, device)
|
||||||
|
|
||||||
|
async def transcribe_audio(audio: np.ndarray,
|
||||||
|
model_size: int,
|
||||||
|
language: Optional[str] = None,
|
||||||
|
device: DeviceType = DeviceType.cpu) -> Transcription:
|
||||||
|
|
||||||
|
if language == "auto":
|
||||||
|
language = None
|
||||||
|
|
||||||
|
# Load the model
|
||||||
|
model = FasterWhisperBackend(model_size=model_size, device=device)
|
||||||
|
model.get_model()
|
||||||
|
model.load()
|
||||||
|
# Transcribe the file
|
||||||
|
return model.transcribe(audio, silent=True, language=language)
|
||||||
Reference in New Issue
Block a user