Montevoice: первая публикация кода
Сервис аудиосозвонов с автоматическим протоколом, работает с 10 августа 2026 года. Открыт по замечанию @decentrail: закрытый код без трекера означает, что замечания некуда нести, кроме чата. Не входит: конфигурация с ключами, записи созвонов, модели синтеза речи.
This commit is contained in:
commit
c7f91eb4b8
11 changed files with 4698 additions and 0 deletions
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
*.env
|
||||||
|
asr-nodes.json
|
||||||
|
agents.json
|
||||||
|
records/
|
||||||
|
venv/
|
||||||
|
say/
|
||||||
|
say-log/
|
||||||
|
backups/
|
||||||
|
__pycache__/
|
||||||
|
*.bak*
|
||||||
|
*.pyc
|
||||||
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) <year> <name of author>
|
||||||
|
|
||||||
|
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/>.
|
||||||
56
README.md
Normal file
56
README.md
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
# Montevoice
|
||||||
|
|
||||||
|
Сервис аудиосозвонов с автоматической расшифровкой. Заходишь по ссылке в браузере,
|
||||||
|
говоришь, а после разговора получаешь протокол: кто что сказал и когда, поимённо, без
|
||||||
|
ручной расшифровки. Записи и протоколы доступны участникам созвона по пропуску.
|
||||||
|
|
||||||
|
Сделан для экосистемы Монтелиберо — сообщества, где созвоны идут постоянно, а решения
|
||||||
|
из них теряются, потому что никто не ведёт стенограмму. Montevoice закрывает именно это:
|
||||||
|
не «ещё одна звонилка», а звонилка, после которой остаётся текст.
|
||||||
|
|
||||||
|
Работает: https://montevoice.aination.center/
|
||||||
|
|
||||||
|
## Что внутри
|
||||||
|
|
||||||
|
- `app.py` — сервер комнат: раздаёт вход, водит бота-рекордера, ведёт поканальную запись
|
||||||
|
(атрибуция говорящих без диаризации), собирает протокол и общую запись, отдаёт страницы.
|
||||||
|
- `asr_server_node.py` — узел распознавания речи: принимает звук по внутренней сети,
|
||||||
|
возвращает сегменты. Считает на своей машине, наружу не ходит.
|
||||||
|
- `voicebot.py` — голосовой участник-агент: слышит, думает, отвечает голосом.
|
||||||
|
- `chat_say.py` — реплика в чат комнаты из внешнего процесса.
|
||||||
|
- `web/` — страницы входа и списка голосов.
|
||||||
|
|
||||||
|
Распознавание — faster-whisper (large-v3-turbo), медиа — LiveKit, синтез речи — piper и silero.
|
||||||
|
|
||||||
|
## Почему свой, а не форк Jitsi
|
||||||
|
|
||||||
|
Честный ответ: потому что нужной части в готовых звонилках нет, а есть она в наших руках.
|
||||||
|
Jitsi, Mumble и прочие решают передачу звука — эту задачу мы не решаем вовсе, её решает
|
||||||
|
LiveKit, который мы взяли готовым. Наша часть начинается после звука: поканальная запись
|
||||||
|
без диаризации, протокол с поимённой атрибуцией и таймкодами, пропуска к записям, голосовой
|
||||||
|
агент как полноправный участник с рукой и трибуной, пул машин для расшифровки. Это
|
||||||
|
надстройка, а не альтернатива.
|
||||||
|
|
||||||
|
Обоснованный упрёк к нам другой: надстройку такого рода правильно делать плагином к зрелому
|
||||||
|
проекту, а не отдельным сервисом — тогда ею смогут пользоваться не только мы. Упрёк принят
|
||||||
|
к рассмотрению всерьёз; если у вас есть довод за конкретную архитектуру, заведите задачу.
|
||||||
|
|
||||||
|
## Замечания и предложения
|
||||||
|
|
||||||
|
Трекер здесь же: [задачи](../../issues). Заводите — читаются.
|
||||||
|
|
||||||
|
Отдельно ценны замечания «как это выглядит снаружи»: разработчик своей поделки их
|
||||||
|
не видит по построению. Несколько правок 31 августа 2026 года пришли ровно так — от
|
||||||
|
человека, который пришёл ругаться на медленную расшифровку и остался разбирать сервис
|
||||||
|
по делу.
|
||||||
|
|
||||||
|
## Состояние
|
||||||
|
|
||||||
|
Работающий сервис, не законченный продукт. Открытые направления и известные дефекты —
|
||||||
|
в задачах. Установка «в один клик» не описана: сервис пока разворачивался только руками
|
||||||
|
и на своих машинах. Если это нужно вам — скажите, опишу.
|
||||||
|
|
||||||
|
## Лицензия
|
||||||
|
|
||||||
|
AGPL-3.0. Сетевой сервис на этом коде обязан оставаться открытым — иначе открытость
|
||||||
|
превращается в одностороннюю выгоду.
|
||||||
153
asr_server_node.py
Normal file
153
asr_server_node.py
Normal file
|
|
@ -0,0 +1,153 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""asr-node — распознавание речи на выделенной машине.
|
||||||
|
|
||||||
|
Городской сервер отдаёт сюда аудио и получает сегменты. Инвариант юрисдикции D7:
|
||||||
|
здесь считается ЗВУК и только звук — ни одного обращения к API моделей отсюда не уходит.
|
||||||
|
Слушает только адрес оверлей-сети, в интернет не выставлен; доступ по bearer-токену.
|
||||||
|
"""
|
||||||
|
import json, os, tempfile, threading, time
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BIND = os.environ.get('ASR_BIND', '100.64.0.4')
|
||||||
|
PORT = int(os.environ.get('ASR_PORT', '8794'))
|
||||||
|
TOKEN = os.environ.get('ASR_TOKEN', '')
|
||||||
|
THREADS = int(os.environ.get('ASR_THREADS', '4'))
|
||||||
|
DEFAULT_MODEL = os.environ.get('ASR_MODEL', 'large-v3-turbo')
|
||||||
|
LOG = Path(os.environ.get('ASR_LOG', '/opt/asr-node/requests.jsonl'))
|
||||||
|
# Окно тишины: на ЛИЧНОЙ машине бывает время, когда она принадлежит человеку.
|
||||||
|
# Тогда узел не уходит совсем, а сжимается до пары потоков — работа продолжается,
|
||||||
|
# но за клавиатурой её не слышно. Пусто = окна нет (так на серверах).
|
||||||
|
QUIET_THREADS = int(os.environ.get('ASR_QUIET_THREADS', '0'))
|
||||||
|
QUIET_DAYS = {int(d) for d in os.environ.get('ASR_QUIET_DAYS', '').replace(' ', '').split(',')
|
||||||
|
if d.isdigit()} # 0=пн … 5=сб, 6=вс
|
||||||
|
QUIET_FROM = os.environ.get('ASR_QUIET_FROM', '09:00')
|
||||||
|
QUIET_TO = os.environ.get('ASR_QUIET_TO', '22:00')
|
||||||
|
TZ_OFFSET = float(os.environ.get('ASR_TZ_OFFSET', '0')) # часы к UTC, для окна по местному времени
|
||||||
|
|
||||||
|
|
||||||
|
def _hm(text):
|
||||||
|
try:
|
||||||
|
h, m = text.split(':')
|
||||||
|
return int(h) * 60 + int(m)
|
||||||
|
except ValueError:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def quiet_now():
|
||||||
|
if not QUIET_THREADS or not QUIET_DAYS:
|
||||||
|
return False
|
||||||
|
now = time.gmtime(time.time() + TZ_OFFSET * 3600)
|
||||||
|
if now.tm_wday not in QUIET_DAYS:
|
||||||
|
return False
|
||||||
|
minutes, start, end = now.tm_hour * 60 + now.tm_min, _hm(QUIET_FROM), _hm(QUIET_TO)
|
||||||
|
return start <= minutes < end if start < end else (minutes >= start or minutes < end)
|
||||||
|
|
||||||
|
|
||||||
|
def threads_now():
|
||||||
|
return QUIET_THREADS if quiet_now() else THREADS
|
||||||
|
|
||||||
|
_models = {}
|
||||||
|
_lock = threading.Lock() # одна расшифровка за раз: 4 ядра делить между запросами хуже,
|
||||||
|
# чем поставить второй запрос в очередь
|
||||||
|
|
||||||
|
|
||||||
|
def get_model(name):
|
||||||
|
from faster_whisper import WhisperModel
|
||||||
|
key = (name, threads_now())
|
||||||
|
if key not in _models:
|
||||||
|
# Сменился режим — старую копию выгружаем: на личной машине память не резиновая.
|
||||||
|
_models.clear()
|
||||||
|
_models[key] = WhisperModel(name, device='cpu', compute_type='int8',
|
||||||
|
cpu_threads=key[1])
|
||||||
|
return _models[key]
|
||||||
|
|
||||||
|
|
||||||
|
class H(BaseHTTPRequestHandler):
|
||||||
|
protocol_version = 'HTTP/1.1'
|
||||||
|
server_version = 'asr-node'
|
||||||
|
|
||||||
|
def log_message(self, *a):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _json(self, code, obj):
|
||||||
|
body = json.dumps(obj, ensure_ascii=False).encode()
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header('Content-Type', 'application/json')
|
||||||
|
self.send_header('Content-Length', str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def _auth(self):
|
||||||
|
if not TOKEN:
|
||||||
|
return True
|
||||||
|
return (self.headers.get('Authorization') or '').replace('Bearer ', '').strip() == TOKEN
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.path == '/health':
|
||||||
|
return self._json(200, {'ok': True,
|
||||||
|
'models_loaded': sorted(name for name, _ in _models),
|
||||||
|
'default_model': DEFAULT_MODEL, 'threads': THREADS,
|
||||||
|
'threads_now': threads_now(), 'quiet': quiet_now(),
|
||||||
|
'busy': _lock.locked()})
|
||||||
|
self._json(404, {'error': 'not found'})
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
if not self.path.startswith('/asr'):
|
||||||
|
return self._json(404, {'error': 'not found'})
|
||||||
|
if not self._auth():
|
||||||
|
return self._json(401, {'error': 'unauthorized'})
|
||||||
|
ctype = self.headers.get('Content-Type', '')
|
||||||
|
length = int(self.headers.get('Content-Length') or 0)
|
||||||
|
if length <= 0 or length > 400 * 1024 * 1024:
|
||||||
|
return self._json(400, {'error': 'bad length'})
|
||||||
|
raw = self.rfile.read(length)
|
||||||
|
language, model_name = 'ru', DEFAULT_MODEL
|
||||||
|
audio = raw
|
||||||
|
if 'multipart/form-data' in ctype:
|
||||||
|
boundary = ctype.split('boundary=')[-1].strip().strip('"').encode()
|
||||||
|
parts = raw.split(b'--' + boundary)
|
||||||
|
audio = None
|
||||||
|
for part in parts:
|
||||||
|
head, _, body = part.partition(b'\r\n\r\n')
|
||||||
|
if b'name="file"' in head:
|
||||||
|
audio = body.rstrip(b'\r\n-')
|
||||||
|
elif b'name="language"' in head:
|
||||||
|
language = body.strip().decode('utf8', 'replace') or 'ru'
|
||||||
|
elif b'name="model"' in head:
|
||||||
|
model_name = body.strip().decode('utf8', 'replace') or DEFAULT_MODEL
|
||||||
|
if audio is None:
|
||||||
|
return self._json(400, {'error': 'no file part'})
|
||||||
|
started = time.time()
|
||||||
|
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
|
||||||
|
f.write(audio)
|
||||||
|
path = f.name
|
||||||
|
try:
|
||||||
|
with _lock:
|
||||||
|
model = get_model(model_name)
|
||||||
|
segs, info = model.transcribe(path, language=(language or None), vad_filter=True,
|
||||||
|
beam_size=1, condition_on_previous_text=False)
|
||||||
|
out = [{'start': float(s.start), 'end': float(s.end), 'text': s.text.strip()}
|
||||||
|
for s in segs if s.text.strip()]
|
||||||
|
wall = round(time.time() - started, 3)
|
||||||
|
audio_sec = round(float(getattr(info, 'duration', 0) or 0), 2)
|
||||||
|
rec = {'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'model': model_name,
|
||||||
|
'audio_sec': audio_sec, 'wall_sec': wall, 'segments': len(out),
|
||||||
|
'ratio': round(wall / audio_sec, 3) if audio_sec else None}
|
||||||
|
with open(LOG, 'a') as f:
|
||||||
|
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
|
||||||
|
self._json(200, {'segments': out, 'model': model_name, 'wall_sec': wall,
|
||||||
|
'audio_sec': audio_sec})
|
||||||
|
except Exception as e:
|
||||||
|
self._json(500, {'error': f'{type(e).__name__}: {str(e)[:200]}'})
|
||||||
|
finally:
|
||||||
|
# Кусок чужого разговора не остаётся на машине ни при каком исходе,
|
||||||
|
# включая падение распознавания. На личных машинах это не мелочь.
|
||||||
|
try:
|
||||||
|
os.unlink(path)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
ThreadingHTTPServer((BIND, PORT), H).serve_forever()
|
||||||
26
chat_say.py
Normal file
26
chat_say.py
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Реплика в чат комнаты от полной сессии Дистилла.
|
||||||
|
|
||||||
|
Голос в комнате ведёт voicebot (быстрый контур через шлюз), а этим каналом
|
||||||
|
в чате присутствует САМА сессия — с каноном, ГТМ и всеми инструментами.
|
||||||
|
Такт сессии — десятки секунд, для чата это нормальная скорость собеседника.
|
||||||
|
"""
|
||||||
|
import asyncio, json, sys, time
|
||||||
|
import app
|
||||||
|
from livekit import rtc
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
room_name, text = sys.argv[1], sys.argv[2]
|
||||||
|
room = rtc.Room()
|
||||||
|
await room.connect(app.WS_LOCAL, app.mk_token(room_name, 'distill-session', 'Дистилл·сессия'))
|
||||||
|
await asyncio.sleep(1.2)
|
||||||
|
message = json.dumps({'v': 1, 'type': 'chat', 'text': text[:2000], 'name': 'Дистилл·сессия',
|
||||||
|
'at': int(time.time() * 1000)}, ensure_ascii=False).encode()
|
||||||
|
await room.local_participant.publish_data(message, reliable=True,
|
||||||
|
topic=f'chat:{room.local_participant.identity}')
|
||||||
|
await asyncio.sleep(1.5)
|
||||||
|
await room.disconnect()
|
||||||
|
print('отправлено')
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
15
hook-transcript.sh
Executable file
15
hook-transcript.sh
Executable file
|
|
@ -0,0 +1,15 @@
|
||||||
|
#!/bin/bash
|
||||||
|
# Called by callhub after each transcript is ready: $1 = record dir
|
||||||
|
D="$1"; ROOM=$(python3 -c "import json,sys;print(json.load(open('$D/meta.json'))['room'])" 2>/dev/null || basename "$D")
|
||||||
|
N=$(python3 -c "import json;print(json.load(open('$D/meta.json'))['entries'])" 2>/dev/null || echo '?')
|
||||||
|
TS=$(date -u +%Y%m%dT%H%M%SZ)
|
||||||
|
cat > "/opt/agent-workspace/bus/queue/call-transcript-$TS.json" <<EOF
|
||||||
|
{
|
||||||
|
"msg_id": "call-transcript-$TS",
|
||||||
|
"from": "callhub",
|
||||||
|
"to": "distill",
|
||||||
|
"type": "notification",
|
||||||
|
"body": "Готов транскрипт созвона «$ROOM»: $D/transcript.md ($N реплик). Аудио поканально + call-mix.ogg там же.",
|
||||||
|
"created_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
1592
voicebot.py
Normal file
1592
voicebot.py
Normal file
File diff suppressed because it is too large
Load diff
37
web/index.html
Normal file
37
web/index.html
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Montevoice — созвоны с автоматическим транскриптом</title>
|
||||||
|
<style>
|
||||||
|
:root{--bg:#0d1117;--card:#161b22;--line:#232b36;--txt:#e6edf3;--dim:#8b949e;--accent:#3b82f6}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{background:var(--bg);color:var(--txt);font-family:system-ui,-apple-system,sans-serif;max-width:520px;margin:0 auto;padding:36px 16px 48px}
|
||||||
|
.brand{display:flex;align-items:center;gap:9px;font-weight:700;font-size:1.05em;letter-spacing:-.01em}
|
||||||
|
.brand .dot{width:9px;height:9px;border-radius:50%;background:var(--accent)}
|
||||||
|
.brand small{font-weight:400;color:var(--dim);font-size:.8em}
|
||||||
|
h1{font-size:1.6em;font-weight:650;margin:20px 0 8px;letter-spacing:-.02em}
|
||||||
|
.note{color:var(--dim);font-size:.95em;line-height:1.55}
|
||||||
|
input,button{font-size:1em;padding:12px 14px;border-radius:10px;border:1px solid var(--line);background:var(--card);color:var(--txt);width:100%;margin-top:10px;font-family:inherit}
|
||||||
|
input:focus{outline:none;border-color:var(--accent)}
|
||||||
|
button{background:var(--accent);border:none;cursor:pointer;font-weight:600}
|
||||||
|
ul{list-style:none;padding:0;margin:22px 0 0}
|
||||||
|
li{display:flex;gap:11px;align-items:flex-start;padding:10px 0;color:var(--dim);font-size:.93em;line-height:1.5;border-top:1px solid var(--line)}
|
||||||
|
li b{color:var(--txt);font-weight:600}
|
||||||
|
.ic{font-size:1.1em;line-height:1.3}
|
||||||
|
a{color:var(--accent);text-decoration:none}
|
||||||
|
</style></head><body>
|
||||||
|
<div class="brand"><span class="dot"></span>Montevoice<small>· Синаполис</small></div>
|
||||||
|
<h1>Созвон, который сам себя записывает</h1>
|
||||||
|
<p class="note">Назовите комнату — и отправьте ссылку собеседникам. Ставить ничего не нужно, регистрироваться тоже.</p>
|
||||||
|
<input id="room" placeholder="Название комнаты" maxlength="48">
|
||||||
|
<button onclick="go()">Создать или войти</button>
|
||||||
|
<ul>
|
||||||
|
<li><span class="ic">🔴</span><div><b>Запись включается сама.</b> Не зависит от того, вспомнил ли кто-то её включить.</div></li>
|
||||||
|
<li><span class="ic">📝</span><div><b>Транскрипт с именами.</b> Голос каждого пишется отдельно, поэтому в тексте видно, кто что сказал.</div></li>
|
||||||
|
<li><span class="ic">✋</span><div><b>Поднятая рука.</b> Очередь видна всем и попадает в транскрипт — слово дают без перебиваний.</div></li>
|
||||||
|
<li><span class="ic">🤖</span><div><b>Агенты как участники.</b> <a href="/voices">Свой голос</a> у каждого; в разговоре молчат, пока не позовут по имени.</div></li>
|
||||||
|
</ul>
|
||||||
|
<script>
|
||||||
|
function go(){var r=document.getElementById('room').value.trim()||('zvonok-'+Math.random().toString(36).slice(2,7));
|
||||||
|
if(!/^[A-Za-zА-Яа-яЁё0-9_-]{1,48}$/.test(r)){alert('Только буквы, цифры, дефис и подчёркивание');return;}
|
||||||
|
location.href=(location.pathname.replace(/\/$/,''))+'/'+encodeURIComponent(r);}
|
||||||
|
document.getElementById('room').addEventListener('keydown',e=>{if(e.key==='Enter')go();});
|
||||||
|
</script></body></html>
|
||||||
340
web/join.html
Normal file
340
web/join.html
Normal file
|
|
@ -0,0 +1,340 @@
|
||||||
|
<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>__ROOM__ — Montevoice</title>
|
||||||
|
<style>
|
||||||
|
:root{--bg:#0d1117;--card:#161b22;--line:#232b36;--txt:#e6edf3;--dim:#8b949e;--accent:#3b82f6;--live:#ef4444;--speak:#22c55e;--hand:#f59e0b}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{background:var(--bg);color:var(--txt);font-family:system-ui,-apple-system,sans-serif;max-width:1080px;margin:0 auto;padding:28px 16px 40px;-webkit-font-smoothing:antialiased}
|
||||||
|
#gate{max-width:520px}
|
||||||
|
.brand{display:flex;align-items:center;gap:9px;font-weight:700;font-size:1.05em;letter-spacing:-.01em}
|
||||||
|
.brand .dot{width:9px;height:9px;border-radius:50%;background:var(--accent)}
|
||||||
|
.brand small{font-weight:400;color:var(--dim);font-size:.8em;letter-spacing:0}
|
||||||
|
h1{font-size:1.45em;font-weight:650;margin:18px 0 6px;letter-spacing:-.02em}
|
||||||
|
.note{color:var(--dim);font-size:.92em;line-height:1.5}
|
||||||
|
input,textarea,button{font-size:1em;padding:12px 14px;border-radius:10px;border:1px solid var(--line);background:var(--card);color:var(--txt);width:100%;margin-top:10px;font-family:inherit}
|
||||||
|
input:focus,textarea:focus{outline:none;border-color:var(--accent)}
|
||||||
|
button{border:none;cursor:pointer;font-weight:600;transition:opacity .15s}
|
||||||
|
button:hover{opacity:.88}
|
||||||
|
button:disabled{opacity:.45;cursor:default}
|
||||||
|
.off{background:#5b2028!important;border-color:#9f3542!important;color:#fecaca}
|
||||||
|
.primary{background:var(--accent)}
|
||||||
|
.sec{background:#21262d;border:1px solid var(--line)}
|
||||||
|
.row{display:flex;gap:8px;flex-wrap:wrap}
|
||||||
|
.row button{margin-top:10px;flex:1 1 150px;width:auto}
|
||||||
|
#gate button{width:100%}
|
||||||
|
.live{display:inline-flex;align-items:center;gap:8px;background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.35);color:#fca5a5;padding:7px 12px;border-radius:999px;font-size:.85em;margin-top:14px}
|
||||||
|
.live .pulse{width:8px;height:8px;border-radius:50%;background:var(--live);animation:pulse 1.8s infinite}
|
||||||
|
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.25}}
|
||||||
|
.stage{display:grid;grid-template-columns:minmax(0,1fr);gap:16px;align-items:start;margin-top:16px}
|
||||||
|
@media(min-width:900px){.stage{grid-template-columns:minmax(0,1fr) 340px}.chat{margin-top:0}}
|
||||||
|
#parts{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:8px}
|
||||||
|
.p{display:flex;align-items:center;gap:10px;padding:10px 12px;min-height:62px;background:var(--card);border:1px solid var(--line);border-radius:12px;transition:border-color .2s}
|
||||||
|
.p.speak{border-color:var(--speak)}
|
||||||
|
.av{width:36px;height:36px;min-width:36px;border-radius:50%;display:grid;place-items:center;font-size:17px;background:#1f2937;position:relative}
|
||||||
|
.p.bot .av{background:#1e293b}
|
||||||
|
.p.speak .av::after{content:'';position:absolute;inset:-4px;border-radius:50%;border:2px solid var(--speak);animation:ring 1.2s ease-out infinite}
|
||||||
|
@keyframes ring{0%{transform:scale(.9);opacity:.9}100%{transform:scale(1.15);opacity:0}}
|
||||||
|
.who{flex:1;min-width:0}
|
||||||
|
.nm{font-weight:600;font-size:.95em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||||
|
.rl{color:var(--dim);font-size:.76em;margin-top:1px}
|
||||||
|
.badge{background:rgba(245,158,11,.15);color:var(--hand);border:1px solid rgba(245,158,11,.4);padding:3px 9px;border-radius:999px;font-size:.82em;font-weight:600;white-space:nowrap}
|
||||||
|
.mut{color:var(--dim);font-size:1em}
|
||||||
|
.mutebtn{width:auto;margin:0;padding:4px 8px;background:#21262d;border:1px solid var(--line);border-radius:8px;font-size:.85em;color:var(--dim);opacity:.55}
|
||||||
|
.mutebtn:hover{opacity:1;color:#fca5a5}
|
||||||
|
.floorbtn{width:auto;margin:0;padding:4px 8px;background:#21262d;border:1px solid var(--line);border-radius:8px;font-size:.85em;color:var(--dim);opacity:.6}
|
||||||
|
.floorbtn:hover{opacity:1;color:#93c5fd}
|
||||||
|
.floorbtn.on{background:rgba(59,130,246,.2);border-color:var(--accent);color:#93c5fd;opacity:1}
|
||||||
|
.state{font-size:.74em;margin-top:2px;display:block}
|
||||||
|
.state.thinking,.state.hearing{color:#fcd34d}.state.speaking{color:var(--speak)}.state.listening{color:var(--dim)}
|
||||||
|
.state.done{color:#93c5fd}.state.lost{color:#f87171}.state.floor{color:#93c5fd}
|
||||||
|
.hint{background:rgba(59,130,246,.12);border:1px solid rgba(59,130,246,.4);color:#93c5fd;padding:10px 13px;border-radius:10px;font-size:.9em;margin-top:12px;line-height:1.45}
|
||||||
|
.hint.warn{background:rgba(245,158,11,.12);border-color:rgba(245,158,11,.45);color:#fcd34d}
|
||||||
|
button.off{background:#7f1d1d;border:1px solid #b91c1c}
|
||||||
|
#status{color:var(--dim);font-size:.84em;margin-top:16px;line-height:1.5}
|
||||||
|
#err{color:#f87171;font-size:.9em;margin-top:10px}
|
||||||
|
.transcript{margin-top:14px;padding:12px;background:var(--card);border:1px solid var(--line);border-radius:10px;display:flex;align-items:center;gap:8px}.transcript a{color:#60a5fa;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.transcript button{width:auto;margin:0;padding:7px 10px}.history{margin-top:22px}.history a{display:block;color:#60a5fa;margin:8px 0}
|
||||||
|
.chat{margin-top:16px;position:relative}.chat h2{font-size:1.05em;margin:0 0 8px}.chatlog{height:min(52vh,420px);overflow-y:auto;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px}.chatmsg{margin:8px 0;white-space:pre-wrap;overflow-wrap:anywhere}.chatmeta{color:var(--dim);font-size:.78em;margin-bottom:2px}.chatnote{color:var(--dim);font-size:.82em;text-align:center;padding:5px}.chat textarea{resize:vertical;min-height:48px;max-height:140px}.unread{position:absolute;right:8px;bottom:65px;width:auto;margin:0;padding:5px 9px;border-radius:999px;background:var(--accent);font-size:.78em}
|
||||||
|
</style></head><body>
|
||||||
|
<div class="brand"><span class="dot"></span>Montevoice<small>· Синаполис</small></div>
|
||||||
|
|
||||||
|
<div id="gate">
|
||||||
|
<h1>«__ROOM__»</h1>
|
||||||
|
<p class="note">Аудиосозвон по ссылке. Разговор записывается и превращается в текст автоматически — включать запись вручную не нужно.</p>
|
||||||
|
<input id="name" placeholder="Ваше имя" maxlength="40" autocomplete="name">
|
||||||
|
<button id="joinbtn" class="primary">Войти в созвон</button>
|
||||||
|
<div id="err"></div>
|
||||||
|
<div id="history" class="history"></div>
|
||||||
|
<p class="note"><a id="roomArchiveGate" target="_blank" rel="noopener" style="color:#60a5fa">Протоколы прошлых созвонов в этой комнате</a></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="call" hidden>
|
||||||
|
<h1>«__ROOM__»</h1>
|
||||||
|
<div class="live"><span class="pulse"></span>Идёт запись</div>
|
||||||
|
<div id="micnote" class="hint">Микрофон выключен — нажмите «Микрофон», чтобы вас услышали</div>
|
||||||
|
<div id="ownernote" class="hint" hidden></div>
|
||||||
|
<div id="netnote" class="hint warn" hidden></div>
|
||||||
|
<div id="micdenied" class="hint warn" hidden>Браузер не дал доступ к микрофону. Проверьте по порядку: 1) микрофон включён в системе; 2) в адресной строке разрешите сайту доступ к микрофону; 3) микрофон не занят другой программой. После этого нажмите «Микрофон» ещё раз.</div>
|
||||||
|
<div class="stage">
|
||||||
|
<div>
|
||||||
|
<div id="parts"></div>
|
||||||
|
<div class="row"><button id="mute" class="sec">🎙 Микрофон включён</button><button id="hand" class="sec">✋ Поднять руку</button></div>
|
||||||
|
<div class="row"><button id="reaudio" class="sec">🔈 Пропал звук</button><button id="finish" class="sec" hidden>⏹ Завершить созвон</button><button id="leave" class="sec">Выйти</button></div>
|
||||||
|
<div id="transcript" class="transcript" hidden><a id="transcriptLink" target="_blank" rel="noopener"></a><button id="copyTranscript" class="sec">Скопировать</button></div>
|
||||||
|
<div class="transcript"><a id="roomArchive" target="_blank" rel="noopener">Все протоколы этой комнаты</a></div>
|
||||||
|
<div id="status">Транскрипт с именами и таймкодами соберётся сам, когда все выйдут. Поднятая рука видна всем и попадает в транскрипт — ведущий увидит, кто просит слова. «Завершить созвон» закрывает запись сразу для всех, даже если кто-то забыл выйти.</div>
|
||||||
|
</div>
|
||||||
|
<section class="chat"><h2>Чат</h2><div id="chatlog" class="chatlog"><div class="chatnote">Показаны только сообщения после вашего входа. Полная запись останется в транскрипте.</div></div><button id="unread" class="unread" hidden></button><textarea id="chatinput" maxlength="2000" placeholder="Сообщение — Enter отправить, Shift+Enter перенос"></textarea></section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/livekit-client@2/dist/livekit-client.umd.min.js"></script>
|
||||||
|
<script>
|
||||||
|
const $=id=>document.getElementById(id);const ROOM='__ROOM__';
|
||||||
|
const BASE=location.pathname.replace(/\/[^/]*$/,'')||'';
|
||||||
|
const SIGNAL_VERSION=1;let room,muted=false,handRaisedAt=null,unread=0,owner='',ownerName='';
|
||||||
|
const floors=new Set(),agentStates=new Map();const hands=new Map();
|
||||||
|
const HIDDEN=['recorder-bot'];
|
||||||
|
const TRANSCRIPT_KEY='montevoice:transcript:'+ROOM,HISTORY_KEY='montevoice:transcripts';
|
||||||
|
// Стабильная метка вкладки: при повторном входе сервер выдаёт ту же identity,
|
||||||
|
// LiveKit вышибает зависшую прошлую сессию — не остаётся двух плашек одного человека.
|
||||||
|
let CID=localStorage.getItem('montevoice:cid');
|
||||||
|
if(!CID){CID=Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6);localStorage.setItem('montevoice:cid',CID);}
|
||||||
|
$('name').value=localStorage.getItem('callname')||'';
|
||||||
|
// Архив комнаты открывается пропуском — токеном протокола, который есть только
|
||||||
|
// у того, кто в этой комнате был. По одному имени комнаты список не показывается.
|
||||||
|
function archiveHref(){
|
||||||
|
const saved=localStorage.getItem(TRANSCRIPT_KEY)||'';
|
||||||
|
const token=(saved.match(/\/t\/([^/?#]+)/)||[])[1];
|
||||||
|
return token?(BASE+'/r/'+encodeURIComponent(ROOM)+'?t='+encodeURIComponent(token)):'';
|
||||||
|
}
|
||||||
|
function applyArchiveLinks(){
|
||||||
|
const href=archiveHref();
|
||||||
|
for(const id of ['roomArchive','roomArchiveGate']){
|
||||||
|
const el=$(id);if(!el)continue;
|
||||||
|
el.href=href||'#';
|
||||||
|
const box=id==='roomArchive'?el.parentElement:el.parentElement;
|
||||||
|
if(box)box.hidden=!href;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
applyArchiveLinks();
|
||||||
|
showHistory();
|
||||||
|
$('joinbtn').onclick=join;
|
||||||
|
$('name').addEventListener('keydown',e=>{if(e.key==='Enter')join();});
|
||||||
|
function isBot(p){const id=(p.identity||'').toLowerCase();
|
||||||
|
return id.endsWith('-voice')||id.startsWith('distill-')||/^(echo|arkhivolt|nodus|isaac|rin|murr|faber|alter-victor)[-.]/.test(id);}
|
||||||
|
function isHidden(p){return HIDDEN.some(h=>(p.identity||'').toLowerCase().startsWith(h));}
|
||||||
|
async function join(){
|
||||||
|
const name=$('name').value.trim()||'гость';
|
||||||
|
localStorage.setItem('callname',name);
|
||||||
|
$('joinbtn').disabled=true;$('err').textContent='';
|
||||||
|
try{
|
||||||
|
const r=await fetch(BASE+'/api/token?room='+encodeURIComponent(ROOM)+'&name='+encodeURIComponent(name)+'&cid='+encodeURIComponent(CID));
|
||||||
|
const j=await r.json();
|
||||||
|
if(!j.token)throw new Error(j.error||'нет токена');
|
||||||
|
room=new LivekitClient.Room();
|
||||||
|
room.on('trackSubscribed',t=>{if(t.kind==='audio'){const el=t.attach();el.dataset.audioSink='1';document.body.appendChild(el);}});
|
||||||
|
room.on('reconnecting',()=>{$('netnote').textContent='Связь потеряна — переподключаюсь…';$('netnote').hidden=false;});
|
||||||
|
room.on('reconnected',()=>{$('netnote').hidden=true;reattachAudio();});
|
||||||
|
room.on('participantConnected',render);
|
||||||
|
room.on('participantDisconnected',p=>{hands.delete(p.identity);if(p.identity===owner){owner='';ownerName='';applyOwner();}render();});
|
||||||
|
room.on('activeSpeakersChanged',render);
|
||||||
|
room.on('trackMuted',render);room.on('trackUnmuted',render);
|
||||||
|
room.on('dataReceived',(payload,participant)=>onData(payload,participant));
|
||||||
|
room.on('disconnected',()=>{$('call').hidden=true;$('gate').hidden=false;$('joinbtn').disabled=false;showHistory();});
|
||||||
|
await room.connect(j.url,j.token);
|
||||||
|
await room.localParticipant.setMicrophoneEnabled(false);muted=true;
|
||||||
|
$('mute').textContent='🔇 Микрофон выключен';$('mute').classList.add('off');
|
||||||
|
await publishSignal({v:SIGNAL_VERSION,type:'hand-state-request'});
|
||||||
|
$('gate').hidden=true;$('call').hidden=false;render();
|
||||||
|
}catch(e){$('err').textContent='Не удалось подключиться: '+e.message;$('joinbtn').disabled=false;}
|
||||||
|
}
|
||||||
|
function micOff(p){try{const t=[...p.audioTrackPublications.values()][0];return t?t.isMuted:false;}catch{return false;}}
|
||||||
|
function render(){
|
||||||
|
if(!room)return;
|
||||||
|
const ps=[room.localParticipant,...room.remoteParticipants.values()].filter(p=>!isHidden(p));
|
||||||
|
const queue=[...hands.entries()].sort((a,b)=>a[1]-b[1]||a[0].localeCompare(b[0]));
|
||||||
|
const pos=new Map(queue.map(([id],i)=>[id,i+1]));
|
||||||
|
const ordered=[...ps].sort((a,b)=>{const ap=pos.get(a.identity),bp=pos.get(b.identity);return ap&&bp?ap-bp:ap?-1:bp?1:ps.indexOf(a)-ps.indexOf(b);});
|
||||||
|
// Рука опускается сама, когда человек заговорил: её постоянно забывают снять.
|
||||||
|
if(handRaisedAt!==null&&!muted&&room.localParticipant.isSpeaking)lowerHand();
|
||||||
|
const html=ordered.map(p=>{
|
||||||
|
const n=pos.get(p.identity),bot=isBot(p),me=p===room.localParticipant;
|
||||||
|
return '<div data-id="'+esc(p.identity)+'" class="p'+(p.isSpeaking?' speak':'')+(bot?' bot':'')+'">'+
|
||||||
|
'<div class="av">'+(bot?'🤖':'👤')+'</div>'+
|
||||||
|
'<div class="who"><div class="nm">'+esc(p.name||p.identity)+(me?' <span style="color:var(--dim);font-weight:400">(вы)</span>':'')+'</div>'+
|
||||||
|
'<div class="rl">'+(bot?'агент города':'человек')+'</div>'+(bot?stateLine(p.identity):'')+'</div>'+
|
||||||
|
(micOff(p)?'<span class="mut" title="микрофон выключен">🔇</span>':
|
||||||
|
(me||!isOwner())?'':'<button class="mutebtn" data-mute="'+esc(p.identity)+'" title="выключить микрофон этому участнику">🔇</button>')+
|
||||||
|
((bot&&isOwner())?'<button class="floorbtn'+(floors.has(p.identity)?' on':'')+'" data-floor="'+esc(p.identity)+'" title="'+(floors.has(p.identity)?'забрать трибуну':'дать слово как основному докладчику: агента не будут перебивать')+'">🎤</button>':'')+
|
||||||
|
(n?'<span class="badge">✋ '+n+'</span>':'')+'</div>';}).join('');
|
||||||
|
// Без изменений DOM не трогаем вовсе: перерисовка раз в секунду давала
|
||||||
|
// дрожание списка в Firefox (сообщил kirill на созвоне 12.08).
|
||||||
|
if($('parts').dataset.sig===html)return;
|
||||||
|
const before=new Map([...$('parts').children].map(el=>[el.dataset.id,el.getBoundingClientRect().top]));
|
||||||
|
$('parts').innerHTML=html;$('parts').dataset.sig=html;
|
||||||
|
[...$('parts').children].forEach(el=>{const old=before.get(el.dataset.id),now=el.getBoundingClientRect().top;
|
||||||
|
if(old!==undefined&&Math.abs(old-now)>1){el.style.transform=`translateY(${old-now}px)`;el.style.transition='none';
|
||||||
|
requestAnimationFrame(()=>{el.style.transition='transform .28s ease,border-color .2s';el.style.transform='translateY(0)';});}});
|
||||||
|
}
|
||||||
|
$('parts').addEventListener('click',async e=>{
|
||||||
|
const floorBtn=e.target.closest('[data-floor]');
|
||||||
|
if(floorBtn&&room){
|
||||||
|
const id=floorBtn.dataset.floor,granted=!floors.has(id);
|
||||||
|
floorBtn.disabled=true;setTimeout(()=>{floorBtn.disabled=false;},600);
|
||||||
|
await publishSignal({v:SIGNAL_VERSION,type:'floor',target:id,granted,at:Date.now()});
|
||||||
|
if(granted)floors.add(id);else floors.delete(id);
|
||||||
|
$('parts').dataset.sig='';render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const btn=e.target.closest('[data-mute]');if(!btn||!room)return;
|
||||||
|
const id=btn.dataset.mute;
|
||||||
|
if(!confirm('Выключить микрофон участнику? Это увидят все — действие попадёт в протокол.'))return;
|
||||||
|
btn.disabled=true;
|
||||||
|
await publishSignal({v:SIGNAL_VERSION,type:'mute',target:id,at:Date.now()});
|
||||||
|
});
|
||||||
|
// Ведущий — тот, кто создал комнату (вошёл первым). Только у него кнопки глушения и
|
||||||
|
// завершения: иначе один вандал глушит всех и обрывает мероприятие.
|
||||||
|
function isOwner(){return !!room&&owner===room.localParticipant.identity;}
|
||||||
|
function applyOwner(){
|
||||||
|
const mine=isOwner();
|
||||||
|
$('finish').hidden=!mine;
|
||||||
|
$('ownernote').textContent=mine
|
||||||
|
? 'Вы ведущий этой комнаты: можете выключать микрофоны участникам и завершать созвон.'
|
||||||
|
: (ownerName?('Ведущий комнаты: '+ownerName+' — глушение микрофонов и завершение созвона у него.'):'');
|
||||||
|
$('ownernote').hidden=!$('ownernote').textContent;
|
||||||
|
$('parts').dataset.sig='';render();
|
||||||
|
}
|
||||||
|
// Что сейчас с агентом: люди не должны ловить тишину и гадать, думает он или отвалился.
|
||||||
|
const STATE_WORDS={hearing:'разбирает сказанное…',thinking:'думает…',speaking:'говорит',listening:'слушает',done:'закончил',
|
||||||
|
skipped:'решил не отвечать',error:'сбой у агента',floor:'на трибуне'};
|
||||||
|
function stateLine(identity){
|
||||||
|
const st=agentStates.get(identity);
|
||||||
|
if(!st)return '';
|
||||||
|
const stale=Date.now()-st.at>12000;
|
||||||
|
const key=stale?'lost':st.state;
|
||||||
|
const word=stale?'нет ответа':(STATE_WORDS[st.state]||st.state);
|
||||||
|
const floor=floors.has(identity)?' · трибуна':'';
|
||||||
|
return '<span class="state '+esc(key)+'">'+esc(word+floor)+'</span>';
|
||||||
|
}
|
||||||
|
function esc(s){const d=document.createElement('div');d.textContent=s;return d.innerHTML;}
|
||||||
|
async function publishSignal(message){
|
||||||
|
if(!room)return;
|
||||||
|
const options={reliable:true};if(message.type==='chat')options.topic='chat:'+room.localParticipant.identity;
|
||||||
|
await room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(message)),options);
|
||||||
|
}
|
||||||
|
async function onData(payload,participant){
|
||||||
|
let m;try{m=JSON.parse(new TextDecoder().decode(payload));}catch{return;}
|
||||||
|
if(m.v!==SIGNAL_VERSION)return;
|
||||||
|
if(m.type==='transcript'&&typeof m.url==='string'){saveTranscript(m.url);return;}
|
||||||
|
if(m.type==='agentstate'&&participant){
|
||||||
|
agentStates.set(participant.identity,{state:m.state,floor:!!m.floor,at:Date.now()});
|
||||||
|
if(m.floor)floors.add(participant.identity);else floors.delete(participant.identity);
|
||||||
|
$('parts').dataset.sig='';render();return;
|
||||||
|
}
|
||||||
|
if(m.type==='floor'&&typeof m.target==='string'){
|
||||||
|
if(m.granted)floors.add(m.target);else floors.delete(m.target);
|
||||||
|
$('parts').dataset.sig='';render();return;
|
||||||
|
}
|
||||||
|
if(m.type==='owner'&&typeof m.identity==='string'){
|
||||||
|
owner=m.identity;ownerName=m.name||m.identity;applyOwner();return;
|
||||||
|
}
|
||||||
|
if(m.type==='mute'&&typeof m.target==='string'){
|
||||||
|
if(room&&m.target===room.localParticipant.identity){
|
||||||
|
muted=true;$('mute').textContent='🔇 Микрофон выключен';$('mute').classList.add('off');$('micnote').hidden=false;
|
||||||
|
$('status').textContent='Ваш микрофон выключил'+(participant?' '+(participant.name||participant.identity):' другой участник')+'. Включить обратно можно кнопкой «Микрофон».';
|
||||||
|
}
|
||||||
|
render();return;
|
||||||
|
}
|
||||||
|
if(m.type==='end'){
|
||||||
|
$('status').textContent='Созвон завершён'+(participant?' участником '+(participant.name||participant.identity):'')+'. Запись закрывается, транскрипт появится по ссылке.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(m.type==='chat'&&participant&&typeof m.text==='string'){
|
||||||
|
addChat(participant,m.text.slice(0,2000),Number(m.at)||Date.now());return;
|
||||||
|
}
|
||||||
|
if(m.type==='hand-state-request'){
|
||||||
|
if(handRaisedAt!==null)await publishSignal({v:SIGNAL_VERSION,type:'hand',action:'status',raised:true,raisedAt:handRaisedAt});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(m.type!=='hand'||!participant)return;
|
||||||
|
if(m.raised)hands.set(participant.identity,Number(m.raisedAt));else hands.delete(participant.identity);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
function addChat(participant,text,at){
|
||||||
|
const log=$('chatlog'),atBottom=log.scrollHeight-log.scrollTop-log.clientHeight<24;
|
||||||
|
const row=document.createElement('div');row.className='chatmsg';
|
||||||
|
row.innerHTML='<div class="chatmeta">'+(isBot(participant)?'🤖 ':'')+esc(participant.name||participant.identity)+' · '+esc(new Date(at).toLocaleTimeString('ru-RU',{hour:'2-digit',minute:'2-digit'}))+'</div><div>'+esc(text)+'</div>';
|
||||||
|
log.appendChild(row);
|
||||||
|
if(atBottom){log.scrollTop=log.scrollHeight;}else{unread++;$('unread').textContent='Новых: '+unread;$('unread').hidden=false;}
|
||||||
|
}
|
||||||
|
$('chatlog').addEventListener('scroll',()=>{const e=$('chatlog');if(e.scrollHeight-e.scrollTop-e.clientHeight<24){unread=0;$('unread').hidden=true;}});
|
||||||
|
$('unread').onclick=()=>{$('chatlog').scrollTop=$('chatlog').scrollHeight;unread=0;$('unread').hidden=true;};
|
||||||
|
$('chatinput').addEventListener('keydown',async e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();const text=e.target.value.slice(0,2000);if(!text.trim()||!room)return;e.target.value='';const at=Date.now();await publishSignal({v:SIGNAL_VERSION,type:'chat',text,at,name:room.localParticipant.name||''});addChat(room.localParticipant,text,at);}});
|
||||||
|
setInterval(()=>{if(agentStates.size)$('parts').dataset.sig='';render();},1000);
|
||||||
|
async function lowerHand(){
|
||||||
|
if(handRaisedAt===null)return;
|
||||||
|
handRaisedAt=null;hands.delete(room.localParticipant.identity);
|
||||||
|
$('hand').textContent='✋ Поднять руку';$('hand').classList.remove('off');
|
||||||
|
await publishSignal({v:SIGNAL_VERSION,type:'hand',action:'change',raised:false,raisedAt:null});
|
||||||
|
}
|
||||||
|
$('mute').onclick=async()=>{
|
||||||
|
const want=muted; // хотим включить микрофон, если он сейчас выключен
|
||||||
|
try{
|
||||||
|
await room.localParticipant.setMicrophoneEnabled(want);
|
||||||
|
$('micdenied').hidden=true;
|
||||||
|
}catch(e){
|
||||||
|
if(want){$('micdenied').hidden=false;return;}
|
||||||
|
}
|
||||||
|
muted=!want;
|
||||||
|
$('mute').textContent=muted?'🔇 Микрофон выключен':'🎙 Микрофон включён';$('mute').classList.toggle('off',muted);$('micnote').hidden=!muted;
|
||||||
|
// Включил микрофон — значит собрался говорить: рука больше не нужна (Andy, 12.08).
|
||||||
|
if(!muted)await lowerHand();
|
||||||
|
render();
|
||||||
|
};
|
||||||
|
$('hand').onclick=async()=>{
|
||||||
|
handRaisedAt=handRaisedAt===null?Date.now():null;
|
||||||
|
if(handRaisedAt===null)hands.delete(room.localParticipant.identity);
|
||||||
|
else hands.set(room.localParticipant.identity,handRaisedAt);
|
||||||
|
await publishSignal({v:SIGNAL_VERSION,type:'hand',action:'change',raised:handRaisedAt!==null,raisedAt:handRaisedAt});
|
||||||
|
$('hand').textContent=handRaisedAt===null?'✋ Поднять руку':'✋ Рука поднята';$('hand').classList.toggle('off',handRaisedAt!==null);render();
|
||||||
|
};
|
||||||
|
// «Звук пропал» без разрыва сессии — жалоба kirill 12.08: помогал только перезаход.
|
||||||
|
// Дорожки переприкрепляются заново, оставаться в комнате при этом не нужно бросать.
|
||||||
|
function reattachAudio(){
|
||||||
|
if(!room)return;
|
||||||
|
document.querySelectorAll('[data-audio-sink]').forEach(el=>el.remove());
|
||||||
|
let n=0;
|
||||||
|
room.remoteParticipants.forEach(p=>p.audioTrackPublications.forEach(pub=>{
|
||||||
|
if(pub.track){const el=pub.track.attach();el.dataset.audioSink='1';document.body.appendChild(el);n++;}
|
||||||
|
}));
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
$('reaudio').onclick=()=>{
|
||||||
|
const n=reattachAudio();
|
||||||
|
$('netnote').textContent=n?('Звук переподключён — дорожек: '+n+'. Если тишина осталась, проверьте громкость и выбранное устройство вывода.')
|
||||||
|
:'Сейчас никто не передаёт звук — переподключать нечего.';
|
||||||
|
$('netnote').hidden=false;setTimeout(()=>{$('netnote').hidden=true;},6000);
|
||||||
|
};
|
||||||
|
$('leave').onclick=()=>room.disconnect();
|
||||||
|
$('finish').onclick=async()=>{
|
||||||
|
if(!room)return;
|
||||||
|
if(!confirm('Завершить созвон для всех? Запись закроется и уйдёт в расшифровку.'))return;
|
||||||
|
$('finish').disabled=true;
|
||||||
|
await publishSignal({v:SIGNAL_VERSION,type:'end',at:Date.now()});
|
||||||
|
$('status').textContent='Созвон завершён. Запись закрывается, транскрипт появится по ссылке.';
|
||||||
|
setTimeout(()=>room.disconnect(),700);
|
||||||
|
};
|
||||||
|
function saveTranscript(url){
|
||||||
|
if(localStorage.getItem(TRANSCRIPT_KEY)===url){showHistory();return;}
|
||||||
|
localStorage.setItem(TRANSCRIPT_KEY,url);let list=[];try{list=JSON.parse(localStorage.getItem(HISTORY_KEY)||'[]');}catch{}
|
||||||
|
list=[{room:ROOM,url,at:Date.now()},...list.filter(x=>x&&x.url!==url)].slice(0,10);localStorage.setItem(HISTORY_KEY,JSON.stringify(list));
|
||||||
|
$('transcriptLink').href=url;$('transcriptLink').textContent='Транскрипт этого созвона';$('transcript').hidden=false;applyArchiveLinks();showHistory();
|
||||||
|
}
|
||||||
|
function showHistory(){
|
||||||
|
let list=[];try{list=JSON.parse(localStorage.getItem(HISTORY_KEY)||'[]');}catch{}
|
||||||
|
$('history').innerHTML=list.length?'<h2>Транскрипты ваших созвонов</h2>'+list.slice(0,10).map(x=>'<a href="'+esc(x.url)+'" target="_blank" rel="noopener">«'+esc(x.room)+'» — '+new Date(x.at).toLocaleString('ru-RU')+'</a>').join(''):'';
|
||||||
|
const saved=localStorage.getItem(TRANSCRIPT_KEY);if(saved){$('transcriptLink').href=saved;$('transcriptLink').textContent='Транскрипт этого созвона';$('transcript').hidden=false;}
|
||||||
|
applyArchiveLinks();
|
||||||
|
}
|
||||||
|
$('copyTranscript').onclick=async()=>{await navigator.clipboard.writeText($('transcriptLink').href);$('copyTranscript').textContent='Скопировано';setTimeout(()=>$('copyTranscript').textContent='Скопировать',1200);};
|
||||||
|
</script></body></html>
|
||||||
28
web/voices.html
Normal file
28
web/voices.html
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Голоса агентов — Montevoice</title>
|
||||||
|
<style>body{background:#101418;color:#e8e8e8;font-family:system-ui,sans-serif;max-width:520px;margin:40px auto;padding:0 16px}
|
||||||
|
h1{font-size:1.3em}h2{font-size:1.1em;margin-top:28px}.v{background:#1a2026;border-radius:10px;padding:14px;margin:10px 0}
|
||||||
|
.n{font-weight:600;margin-bottom:8px}audio{width:100%}
|
||||||
|
.note{color:#9ca3af;font-size:.9em}code{background:#0b0e11;padding:2px 6px;border-radius:5px}</style></head><body>
|
||||||
|
<h1>Голоса агентов — Montevoice</h1>
|
||||||
|
<p class="note">Каждый агент выбирает голос себе сам — правит свою запись в реестре
|
||||||
|
<code>organs/calls/agents.json</code> на городском сервере. Ключ записи — его identity в созвоне.</p>
|
||||||
|
<h2>Piper</h2>
|
||||||
|
<div class="v"><div class="n">dmitri — мужской, ровный</div><audio controls src="voices/dmitri.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">denis — мужской, мягче</div><audio controls src="voices/denis.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">ruslan — мужской, ниже</div><audio controls src="voices/ruslan.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">irina — женский</div><audio controls src="voices/irina.ogg"></audio></div>
|
||||||
|
<h2>Silero</h2>
|
||||||
|
<div class="v"><div class="n">aidar — мужской</div><audio controls src="voices/silero-aidar.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">baya — женский</div><audio controls src="voices/silero-baya.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">kseniya — женский</div><audio controls src="voices/silero-kseniya.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">xenia — женский</div><audio controls src="voices/silero-xenia.ogg"></audio></div>
|
||||||
|
<div class="v"><div class="n">eugene — мужской</div><audio controls src="voices/silero-eugene.ogg"></audio></div>
|
||||||
|
<p class="note">Голоса Silero распространяются по лицензии CC-NC-BY и подходят для использования,
|
||||||
|
пока сервис остаётся некоммерческим.</p>
|
||||||
|
<p class="note">Настройки записи: <code>voice</code> — голос с движком, например
|
||||||
|
<code>piper:denis</code> или <code>silero:xenia</code>; старое значение <code>denis</code>
|
||||||
|
означает <code>piper:denis</code>. <code>speed</code> — темп речи
|
||||||
|
(1.0 обычный, меньше — быстрее), <code>display_name</code> — как агент подписан в комнате.
|
||||||
|
Нужен голос, которого здесь нет (другой язык, другой тембр) — скажи, добавлю в набор.</p>
|
||||||
|
</body></html>
|
||||||
Loading…
Add table
Reference in a new issue