├── .gitignore
├── .gitmodules
├── Dockerfile
├── LICENSE
├── README.md
├── config
├── config.ini
├── requirements.txt
└── sensitive_words.txt
├── init.py
├── main.py
├── requirements.txt
├── resource
└── subtitle.html
├── start.bat
├── start.sh
├── testing
├── blive.py
├── filter.py
├── gpt.py
├── my_old_thread_main.py
├── my_test_process.py
├── obsolete_danmu.py
├── process.py
├── pth2onnx.py
├── sensitive_words.txt
├── test1.py
├── test2.py
├── testPoolQueeu.py
└── testQueue.py
└── tts.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # User
7 | models/*
8 | output/*
9 | my_config.ini
10 | my_sensitive_words.txt
11 | temp.txt
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | pip-wheel-metadata/
30 | share/python-wheels/
31 | *.egg-info/
32 | .installed.cfg
33 | *.egg
34 | MANIFEST
35 |
36 | # PyInstaller
37 | # Usually these files are written by a python script from a template
38 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
39 | *.manifest
40 | *.spec
41 |
42 | # Installer logs
43 | pip-log.txt
44 | pip-delete-this-directory.txt
45 |
46 | # Unit test / coverage reports
47 | htmlcov/
48 | .tox/
49 | .nox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | *.py,cover
57 | .hypothesis/
58 | .pytest_cache/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 | db.sqlite3
68 | db.sqlite3-journal
69 |
70 | # Flask stuff:
71 | instance/
72 | .webassets-cache
73 |
74 | # Scrapy stuff:
75 | .scrapy
76 |
77 | # Sphinx documentation
78 | docs/_build/
79 |
80 | # PyBuilder
81 | target/
82 |
83 | # Jupyter Notebook
84 | .ipynb_checkpoints
85 |
86 | # IPython
87 | profile_default/
88 | ipython_config.py
89 |
90 | # pyenv
91 | .python-version
92 |
93 | # pipenv
94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
97 | # install all needed dependencies.
98 | #Pipfile.lock
99 |
100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
101 | __pypackages__/
102 |
103 | # Celery stuff
104 | celerybeat-schedule
105 | celerybeat.pid
106 |
107 | # SageMath parsed files
108 | *.sage.py
109 |
110 | # Environments
111 | .env
112 | .venv
113 | env/
114 | venv/
115 | ENV/
116 | env.bak/
117 | venv.bak/
118 |
119 | # Spyder project settings
120 | .spyderproject
121 | .spyproject
122 |
123 | # Rope project settings
124 | .ropeproject
125 |
126 | # mkdocs documentation
127 | /site
128 |
129 | # mypy
130 | .mypy_cache/
131 | .dmypy.json
132 | dmypy.json
133 |
134 | # Pyre type checker
135 | .pyre/
136 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "blivedm"]
2 | path = blivedm
3 | url = https://github.com/newreport/blivedm.git
4 | [submodule "MoeGoe"]
5 | path = MoeGoe
6 | url = https://github.com/newreport/MoeGoe.git
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/newreport/vtbai/d5fc86844d36f6dac6068150eb978466e762c23c/Dockerfile
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Function in coding ....
2 | - VTS API 关键字触发表情
3 | - 语句情感推断触发 VTS 表情
4 | - Azure API TTS
5 | - Link CharacterAI 角色扮演最好的 AI
6 | - Multi link 联动
7 | - ChatGLM-6B 本地1
8 | - ChatterBot 本地2
9 | - Twitch & Youtube 平台支持
10 |
11 | # 资源
12 | - [vits](https://github.com/jaywalnut310/vits) vits source
13 | - [MoeGoe](https://github.com/CjangCjengh/MoeGoe.git) vits chinese
14 | - [vits_with_chatgpt-gpt3](https://github.com/Paraworks/vits_with_chatgpt-gpt3) tts 推理参考
15 | - [blivedm](https://github.com/xfgryujk/blivedm/tree/master) 抓取 b 站直播间信息
16 | - [演示模型](https://huggingface.co/newreport/live_tts_default_model/tree/main) vits model (商用请自炼自然人同意的合法声源或用 Azure)
17 |
18 | - # 架构
19 | > 从哔哩哔哩直播间抓取弹幕和礼物,接收后发送给 openai 官方的 chatgpt,等待 gpt 回调消息后使用 vits 进行 tts 推理,然后根据关键字/VTS API 触发表情和 playsound 播放语音, 播放时 vts 根据声音匹配口型
20 |
21 | > 除非公司或大佬,非常不建议手搓 live2d,一是耗时,二是 vts 和 prprlive 配合关键字触发表情快捷键、VTS API 直播效果还可以
22 |
23 | > 本直播流程仅在 win 下测试并通过,理论 linux 和 mac 在合适的 py 环境中也能使用,py 版本为 conda 3.10.10
24 |
25 | > 注:有能者可以同理把老鼠和油管的扩展了,py 线程协程进程鲨我
26 |
27 | ## 工作流
28 | blivedm(抓直播间信息)——>openai(猫娘对话)——>vits(tts 文本转语音)——>vts(语音转口型,快捷键触发表情)——>obs(推流)
29 |
30 | ## 功能
31 | - 支持 api 请求,扩展用,比如联动,语音转文字后请求即可 httt://127.0.0.1:8080?text=你好
32 | - 支持优先级:api>舰长>礼物>SC>弹幕,礼物和弹幕队列容量默认为5/10,满了自动剔除时间线最后的,SC、舰长没有容量限制
33 |
34 | ## 我的开发环境
35 | - CPU:5700G
36 | - GPU:核显
37 | - 主板:华硕 B550m TUF
38 | - 硬盘:凯侠 RC20
39 | - 内存:16*4(3133hz 金百达)
40 | - 电源:台达 300W
41 | - 机箱:X40 5.5L
42 |
43 | > 主要速度慢在请求 openai 和 cpu 推理,用 gpu 会快很多,由于需要检测同音字敏感词以防爆房,故不能使用 SSE
44 |
45 | > obs、vts、雀魂 AI 全开的情况,推理时 cpu 负载约为 70%,理论讲 2k 内预算的丐中丐 5600G 也可以跑,功耗不超过 100W,ITX 都能跑,还要什么自行车,实际情况请用 n 卡 gpu 跑更好
46 |
47 |
48 | # 搭建流程
49 | 请确保您已安装好 [conda](https://newreport.top/2023-02-27/ubuntu-amd-centos-install-conda/)、[obs](https://obsproject.com/)、[vts](https://denchisoft.com/)、[vscode](https://code.visualstudio.com/)
50 | > 请用 conda 新建 python 3.10 环境,launch 了 vscode
51 | ```bash
52 | git clone -b 1.1-py https://github.com/newreport/vtbai.git
53 | cd vtbai
54 | start.bat
55 | # config\my_config.ini 填写房间号和 openai key
56 | python main.py
57 | # 弹幕,将 resource 中的 hmtl 拖到 obs 里
58 | ```
59 |
60 | ]
61 |
--------------------------------------------------------------------------------
/config/config.ini:
--------------------------------------------------------------------------------
1 | [main]
2 | # pro | dev
3 | env = pro
4 | # bili | twitch | ytb
5 | model = bili
6 | [queue]
7 | api_listen = http://0.0.0.0:3939
8 | # 是否联动,联动时只监听 top queue
9 | is_link = false
10 | [bili]
11 | # 房间id,可为短号
12 | roomid = 207640
13 | # 设置最优先id,可以设置自己
14 | topid = 1,2
15 | [twitch]
16 | [ytb]
17 | [openai]
18 | # openai key
19 | key = ***your key***
20 | # 初始人设
21 | nya1 = 你是猫娘,you are in live,我你主人
22 | # openai api 代理,默认 https://api.openai.com/v1
23 | proxy_domain = https://api.openai.com/v1
24 | # 最大上下文
25 | max_context = 3
26 | # gpt-3.5-turbo | gpt-4 | gpt-4-32k
27 | model = gpt-3.5-turbo
28 | [tts]
29 | # 多少毫秒输出一个字
30 | interval_ms = 100
31 | # 最大缓存数量,超过时不再请求openai,即等播放完后再请求
32 | max_wav_queue = 5
33 | # 文本显示时最大断句
34 | max_text_length = 50
35 | # 语音最大断句
36 | # max_tts_length = 200
37 | # 推理模式 cpu | gpu
38 | # infernce_type = cpu
39 |
40 | model_onnx = ./models/model.onnx
41 | model_config = ./models/config.json
42 | model_pth = ./models/model.pth
43 |
44 | # 以下注释由 gpt 编写
45 | # 音频的长度缩放因子,通常用于控制语速。例如,将 length_scale 设置为 1.5 可以使语音变慢,而将其设置为 0.5 可以使语音加速。
46 | length_scale = 1
47 | # 噪声比例,以控制情感,噪声的标准差缩放因子。默认值为 0.667。
48 | noise_scale = 0.667
49 | # 噪声偏差,以控制音速长短,噪声的标准差缩放因子的偏差值。默认值为 0.8。
50 | noise_scale_w = 0.8
51 | speaker_id = 0
52 | # 是否在播放完后自动删除生成的 wav 文件 1 | 0
53 | auto_del_wav = 0
--------------------------------------------------------------------------------
/config/requirements.txt:
--------------------------------------------------------------------------------
1 | opencc
2 | openai
3 | audonnx
4 | playsound
5 | xlrd
6 | xlwt
7 | xlutils
8 | torchvision
9 | asyncio
--------------------------------------------------------------------------------
/config/sensitive_words.txt:
--------------------------------------------------------------------------------
1 | 敏感词1
2 | 敏感词2
--------------------------------------------------------------------------------
/init.py:
--------------------------------------------------------------------------------
1 | import os
2 | import urllib.request as urllib2
3 | from shutil import copyfile
4 |
5 | dirs = ['models','output','output/wav']
6 |
7 | for dir in dirs:
8 | if not os.path.exists(dir):
9 | os.makedirs(dir)
10 |
11 | filenames = ['model.onnx','model.pth','config.json']
12 |
13 | # https://huggingface.co/newreport/live_tts_default_model/resolve/main/model.onnx
14 | # https://huggingface.co/newreport/live_tts_default_model/resolve/main/model.pth
15 | # https://huggingface.co/newreport/live_tts_default_model/resolve/main/config.json
16 | url='https://huggingface.co/newreport/live_tts_default_model/resolve/main/'
17 |
18 | for filename in filenames:
19 | if not os.path.exists('models/'+filename):
20 | print("downloading..."+url+filename)
21 | f = urllib2.urlopen(url+filename)
22 | with open("models/"+filename, "wb") as code:
23 | code.write(f.read())
24 |
25 | configs =['config/my_config.ini','config/my_sensitive_words.txt']
26 | for config in configs:
27 | if not os.path.exists(config):
28 | filename=config.replace("my_","")
29 | copyfile(filename,config)
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | import openai
3 | import asyncio
4 | import _thread
5 | import random
6 | import logging
7 | import blivedm.blivedm as blivedm
8 | import configparser
9 | import uuid
10 | from queue import Queue, PriorityQueue
11 | import json
12 | import time
13 | import requests
14 | import os
15 | import multiprocessing
16 | import datetime
17 | import xlrd
18 | import xlwt
19 | from flask_cors import CORS
20 | import sys
21 | from xlutils.copy import copy
22 | from pypinyin import lazy_pinyin
23 | from flask import Flask, request,jsonify
24 | import tts
25 |
26 | # 配置文件、当前文本、excel(对话列表数据库)、敏感词文本
27 | config_ini = 'config/config.ini'
28 | xlsl_path = 'output/record.xlsx'
29 | sensitive_txt = 'config/sensitive_words.txt'
30 | if os.path.exists('config/my_config.ini'):
31 | config_ini = 'config/my_config.ini'
32 | if os.path.exists('config/my_sensitive_words.txt'):
33 | sensitive_txt = 'config/my_sensitive_words.txt'
34 | con = configparser.ConfigParser()
35 | con.read(config_ini, encoding='utf-8')
36 | main_config = dict(con.items('main'))
37 | queue_config = dict(con.items('queue'))
38 | bili_config = dict(con.items('bili'))
39 | openai_config = dict(con.items('openai'))
40 | tts_config = dict(con.items('tts'))
41 |
42 |
43 | # excel数据库
44 | if os.path.exists(xlsl_path) == False:
45 | workbook = xlwt.Workbook()
46 | sheet = workbook.add_sheet("test") # 在工作簿中新建一个表格
47 | workbook.save(xlsl_path)
48 | print("xls格式表格初始化成功!")
49 | print('当前进程id::' + str(os.getpid()))
50 | def write_excel_xls_append(value):
51 | workbook = xlrd.open_workbook(xlsl_path) # 打开工作簿
52 | sheets = workbook.sheet_names() # 获取工作簿中的所有表格
53 | rows_old = 0
54 | sheetName = str(datetime.date.today())
55 | if sheetName in sheets:
56 | worksheet = workbook.sheet_by_name(sheetName)
57 | rows_old = worksheet.nrows # 获取表格中已存在的数据的行数
58 | new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
59 | if sheetName not in sheets:
60 | new_workbook.add_sheet(sheetName)
61 | new_worksheet = new_workbook.get_sheet(sheetName) # 获取转化后工作簿中的第一个表格
62 | new_worksheet.write(rows_old, 0, value['datetime'])
63 | new_worksheet.write(rows_old, 1, value['user'])
64 | new_worksheet.write(rows_old, 2, value['type'])
65 | new_worksheet.write(rows_old, 3, value['num'])
66 | new_worksheet.write(rows_old, 4, value['action'])
67 | new_worksheet.write(rows_old, 5, value['msg'])
68 | new_worksheet.write(rows_old, 6, value['price'])
69 | new_workbook.save(xlsl_path) # 保存工作簿
70 | if main_config['env'] == 'dev':
71 | print("xls格式表格【追加】写入数据成功!")
72 |
73 |
74 | # 配置openai
75 | openai.api_key = openai_config['key']
76 | openai.api_base = openai_config['proxy_domain']
77 | base_context = [{"role": "system", "content": openai_config['nya1']}]
78 | context_message = []
79 | temp_message = []
80 | async def chatgpt(is_run):
81 | print("运行gpt循环任务")
82 | while is_run:
83 | chatObj = {"name": '', "type": '', 'num': 0,
84 | 'action': '', 'msg': '', 'price': 0}
85 | # 从队列获取信息
86 | try:
87 | if topQue.empty() == False:
88 | chatObj = topQue.get(True, 1)
89 | elif guardQue.empty() == False:
90 | chatObj = guardQue.get(True, 1)
91 | chatObj = chatObj[1]
92 | elif giftQue.empty() == False:
93 | chatObj = giftQue.get(True, 1)
94 | chatObj = chatObj[1]
95 | elif scQue.empty() == False:
96 | chatObj = scQue.get(True, 1)
97 | chatObj = chatObj[1]
98 | elif danmuQue.empty() == False:
99 | chatObj = danmuQue.get(True, 1)
100 | chatObj = chatObj[1]
101 | except Exception as e:
102 | print("-----------ErrorStart--------------")
103 | print(e)
104 | print("gpt获取弹幕异常,当前线程::")
105 | print(chatObj)
106 | print("-----------ErrorEnd--------------")
107 | await asyncio.sleep(2)
108 | continue
109 | # print(chatObj)
110 | # 过滤队列
111 | if len(chatObj['name']) > 0:
112 | if filter_text(chatObj['name']) and filter_text(chatObj['msg']):
113 | send2gpt(chatObj)
114 | else:
115 | await asyncio.sleep(1)
116 |
117 | def send2gpt(msg):
118 |
119 | if main_config['env'] == 'dev':
120 | print('gpt当前进程id::' + str(os.getpid()))
121 | # 向 gpt 发送的消息
122 | send_gpt_msg = ''
123 | # 向 tts 写入的数据
124 | send_vits_msg = ''
125 | if msg['type'] == 'danmu':
126 | send_gpt_msg = msg['name'] + msg['action'] + msg['msg']
127 | send_vits_msg = msg['msg']
128 | elif msg['type'] == 'sc':
129 | send_gpt_msg = msg['name'] + msg['action'] + \
130 | str(msg['price']) + '块钱sc说' + msg['msg']
131 | send_vits_msg = send_gpt_msg
132 | elif msg['type'] == 'guard':
133 | guardType = '舰长'
134 | if msg['price'] > 200:
135 | guardType = '提督'
136 | elif msg['price'] > 2000:
137 | guardType = '总督'
138 | send_gpt_msg = msg['name'] + msg['action'] + \
139 | guardType + '了,花了' + str(msg['price']) + '元'
140 | send_vits_msg = msg['name'] + msg['action'] + guardType + '了'
141 | elif msg['type'] == 'gift':
142 | send_gpt_msg = msg['name'] + msg['action'] + msg['msg']
143 | send_vits_msg = send_gpt_msg
144 | else:
145 | send_gpt_msg = msg['msg']
146 | send_vits_msg = send_gpt_msg
147 |
148 | # 生成上下文
149 | temp_message.append({"role": "user", "content": send_gpt_msg})
150 | # 上下文最大值
151 | if len(temp_message) > 3:
152 | del (temp_message[0])
153 | message = base_context + temp_message
154 |
155 | # 子进程4
156 | # 开启 openai 进程
157 | if tts_que.full() == False:
158 | p = multiprocessing.Process(target=rec2tts, args=(
159 | msg, send_gpt_msg, message, send_vits_msg,tts_que,tts_config))
160 | p.start()
161 | # join 会阻塞当前 gpt 循环线程,但不会阻塞弹幕线程
162 | print("openai请求子进程开启完成")
163 | if tts_que.full():
164 | p.join()
165 |
166 | def rec2tts(msg, send_gpt_msg, message, send_vits_msg,tts_que,tts_config):
167 | print("进入openai chatgpt进程,向gpt发送::" + send_gpt_msg)
168 |
169 | # 对话日志写入 excel
170 | with open('output/' + str(datetime.date.today()) + '.txt', 'a', encoding='utf-8') as a:
171 | a.write(str(datetime.datetime.now()) + "::发送::" + send_gpt_msg + '\n')
172 | a.flush()
173 | write_excel_xls_append({
174 | 'datetime': str(datetime.datetime.now()),
175 | 'user': msg['name'],
176 | 'type': msg['type'],
177 | 'num': msg['num'],
178 | 'action': msg['action'],
179 | 'msg': msg['msg'],
180 | 'price': msg['price']
181 | })
182 |
183 | # 发送并收
184 | response = openai.ChatCompletion.create(
185 | model=openai_config['model'], messages=message)
186 | responseText = str(response['choices'][0]['message']['content'])
187 |
188 | # 敏感词词音过滤
189 | if filter_text(responseText) == False:
190 | print("检测到敏感词内容::" + responseText)
191 | return
192 | print("从gpt接收::" + responseText)
193 | tts_que.put(send_vits_msg)
194 | tts_que.put(responseText)
195 |
196 | # 对话日志
197 | with open('output/' + str(datetime.date.today()) + '.txt', 'a', encoding='utf-8') as a:
198 | a.write(str(datetime.datetime.now()) + "::接收::" + responseText + '\n')
199 | a.flush()
200 | write_excel_xls_append({
201 | 'datetime': str(datetime.datetime.now()),
202 | 'user': 'gpt35',
203 | 'type': '',
204 | 'num': '',
205 | 'action': '说',
206 | 'msg': responseText,
207 | 'price': 0
208 | })
209 |
210 |
211 | # 敏感词
212 | sensitiveF = open(sensitive_txt, 'r', encoding='utf-8')
213 | hanzi_sensitive_word = sensitiveF.readlines()
214 | pinyin_sensitive_word = []
215 | for i in range(len(hanzi_sensitive_word)):
216 | hanzi_sensitive_word[i] = hanzi_sensitive_word[i].replace('\n', '')
217 | pinyin_sensitive_word.append(str.join('', lazy_pinyin(hanzi_sensitive_word[i])))
218 | # 敏感词音检测
219 | def filter_text(text):
220 | # 为上舰时直接过
221 | if text == '-1':
222 | return True
223 | textPY = str.join('', lazy_pinyin(text))
224 | for i in range(len(hanzi_sensitive_word)):
225 | if hanzi_sensitive_word[i] in text or pinyin_sensitive_word[i] in textPY:
226 | return False
227 | return True
228 |
229 |
230 | # tts
231 | tts_que = multiprocessing.Queue(maxsize=int(tts_config['max_wav_queue']))
232 | wav_que = multiprocessing.Queue(maxsize=int(tts_config['max_wav_queue']))
233 |
234 | # bilibili
235 | # 获取真实房间号
236 | roomID = json.loads(str(requests.get('https://api.live.bilibili.com/room/v1/Room/get_info?room_id=' +
237 | bili_config['roomid']).content, encoding="utf-8"))['data']['room_id']
238 | # 最优先队列、sc、礼物、弹幕队列
239 | topQue = Queue(maxsize=0)
240 | # sc 队列
241 | scQue = PriorityQueue(maxsize=0)
242 | # 舰长队列
243 | guardQue = PriorityQueue(maxsize=0)
244 | # 礼物
245 | giftQue = PriorityQueue(maxsize=5)
246 | # 普通弹幕队列
247 | danmuQue = PriorityQueue(maxsize=10)
248 | topIDs = bili_config['topid'].split(',')
249 | async def run_single_client():
250 | # 如果SSL验证失败就把ssl设为False,B站真的有过忘续证书的情况
251 | client = blivedm.BLiveClient(roomID, ssl=True)
252 | print(roomID)
253 | handler = MyHandler()
254 | client.add_handler(handler)
255 | client.start()
256 | try:
257 | await client.join()
258 | finally:
259 | await client.stop_and_close()
260 |
261 | class MyHandler(blivedm.BaseHandler):
262 | async def _on_heartbeat(self, client: blivedm.BLiveClient, message: blivedm.HeartbeatMessage):
263 | print(f'[{client.room_id}] 当前人气值:{message.popularity}')
264 |
265 | async def _on_danmaku(self, client: blivedm.BLiveClient, message: blivedm.DanmakuMessage):
266 | if message.dm_type == 0:
267 | print(f'弹幕:[{client.room_id}] {message.uname}:{message.msg}')
268 | # 权重计算
269 | guardLevel = message.privilege_type
270 | if guardLevel == 0:
271 | guardLevel = 0
272 | elif guardLevel == 3:
273 | guardLevel = 200
274 | elif guardLevel == 2:
275 | guardLevel = 2000
276 | elif guardLevel == 1:
277 | guardLevel = 20000
278 | # 舰长权重,勋章id权重*100,lv权重*100
279 | medalevel = 0
280 | if message.medal_room_id == roomID:
281 | medalevel = message.medal_level * 100
282 | rank = (999999 - message.user_level * 100 -
283 | guardLevel - medalevel - message.user_level * 10 + random.random())
284 | if danmuQue.full():
285 | try:
286 | danmuQue.get(True, 1)
287 | except BaseException:
288 | print("on_danmuku时,get异常")
289 |
290 | queData = {'name': message.uname, 'type': 'danmu', 'num': 1, 'action': '说',
291 | 'msg': message.msg.replace('[', '').replace(']', ''), 'price': 0}
292 | if main_config['env'] == 'dev':
293 | print("前弹幕队列容量:" + str(danmuQue.qsize()))
294 | print("rank:" + str(rank) + ";name:" + message.uname + ";msg:" +
295 | message.msg.replace('[', '').replace(']', ''))
296 | print(queData)
297 | try:
298 | danmuQue.put((rank, queData), True, 2)
299 | except Exception as e:
300 | print("ErrorStart-------------------------")
301 | print(e)
302 | print("put弹幕队列异常")
303 | print(queData)
304 | print("错误" + str(danmuQue.full()))
305 | print("错误" + str(danmuQue.empty()))
306 | print("后弹幕队列容量:" + str(danmuQue.qsize()))
307 | print("ErrorEnd-------------------------")
308 |
309 | async def _on_gift(self, client: blivedm.BLiveClient, message: blivedm.GiftMessage):
310 | if message.coin_type == 'gold':
311 | print(f'礼物::[{client.room_id}] {message.uname} 赠送{message.gift_name}x{message.num}'
312 | f' ({message.coin_type}瓜子x{message.total_coin})')
313 | price = message.total_coin / 1000
314 | if giftQue.full():
315 | giftQue.get(False, 1)
316 | if price > 1:
317 | queData = {"name": message.uname, "type": 'gift', 'num': message.num,
318 | 'action': message.action, 'msg': message.gift_name, 'price': price}
319 | giftQue.put(
320 | (999999 - price + random.random(), queData), True, 1)
321 |
322 | async def _on_buy_guard(self, client: blivedm.BLiveClient, message: blivedm.GuardBuyMessage):
323 | print(f'上舰::[{client.room_id}] {message.username} 购买{message.gift_name}')
324 | queData = {"name": message.username, "type": 'guard', 'num': 1,
325 | 'action': '上', 'msg': '-1', 'price': message.price / 1000}
326 | guardQue.put((message.guard_level + random.random(), queData))
327 |
328 | async def _on_super_chat(self, client: blivedm.BLiveClient, message: blivedm.SuperChatMessage):
329 | print(
330 | f'SC::[{client.room_id}] 醒目留言 ¥{message.price} {message.uname}:{message.message}')
331 | # 名称、类型、数量、动作、消息、价格
332 | queData = {"name": message.uname, "type": 'sc', 'num': 1,
333 | 'action': '发送', 'msg': message.message, 'price': message.price}
334 | scQue.put((999999 - message.price + random.random(), queData))
335 |
336 |
337 | # api
338 | log = logging.getLogger('werkzeug')
339 | log.setLevel(logging.CRITICAL)
340 | app = Flask(__name__)
341 | CORS(app)
342 |
343 | @app.route('/', methods=['GET'])
344 | def putQueue():
345 | message = request.args.get('text', '')
346 | queData = {"name": '-1', "type": 'top', 'num': 1,
347 | 'action': '', 'msg': message, 'price': 0}
348 | topQue.put(queData)
349 | return '1'
350 | @app.route('/subtitle', methods=['GET'])
351 | def subtitle():
352 | # 读取共享内存变量的值
353 | return curr_txt.value
354 |
355 |
356 |
357 | if __name__ == '__main__':
358 | is_run = True
359 | # multiprocessing.set_start_method('spawn')
360 | manager = multiprocessing.Manager()
361 | curr_txt = manager.Value(str, "")
362 |
363 | # 主进程
364 | # chatgpt
365 | _thread.start_new_thread(asyncio.run,(chatgpt(is_run),))
366 | # bilibili
367 | _thread.start_new_thread(asyncio.run,(run_single_client(),))
368 | print('All thread start.')
369 |
370 | # 子进程1、2
371 | # playsound 播放进程
372 | p = multiprocessing.Process(target=tts.play, args=(is_run,tts_config,wav_que,curr_txt))
373 | p.start()
374 |
375 | # 子进程3
376 | # tts 推理进程
377 | p = multiprocessing.Process(target=tts.inference, args=(is_run,tts_config,tts_que,wav_que))
378 | p.start()
379 |
380 | print('All subprocesses start.')
381 |
382 |
383 | # api
384 | app.run("0.0.0.0", 3939)
385 |
386 |
387 | time.sleep(2)
388 | input('input to exit::\n')
389 |
390 | is_run = False
391 | print('All subprocesses done.')
392 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | openai
2 | torchvision
3 | pyaudio
4 | xlrd
5 | xlwt
6 | xlutils
7 | flask
8 | flask_cors
--------------------------------------------------------------------------------
/resource/subtitle.html:
--------------------------------------------------------------------------------
1 |
90 |
91 |
92 |
93 |
94 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/start.bat:
--------------------------------------------------------------------------------
1 | pip install -r requirements.txt
2 | git submodule update
3 | git submodule update --init --recursive
4 | git submodule update --remote
5 | pip install -r blivedm/requirements.txt
6 | pip install -r MoeGoe/requirements.txt
7 | python init.py
--------------------------------------------------------------------------------
/start.sh:
--------------------------------------------------------------------------------
1 | pip install -r requirements.txt
2 | git submodule update
3 | git submodule update --init --recursive
4 | git submodule update --remote
5 | pip install -r blivedm/requirements.txt
6 | pip install -r MoeGoe/requirements.txt
7 | python init.py
--------------------------------------------------------------------------------
/testing/blive.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import asyncio
3 | import random
4 | from queue import Queue, PriorityQueue
5 | import sys
6 | sys.path.append('../')
7 | import blivedm.blivedm as blivedm
8 |
9 |
10 | # 直播间ID的取值看直播间URL
11 | TEST_ROOM_IDS = [
12 | 47867,
13 | ]
14 |
15 |
16 | async def main():
17 | await run_single_client()
18 |
19 |
20 | async def run_single_client():
21 | room_id = random.choice(TEST_ROOM_IDS)
22 | # 如果SSL验证失败就把ssl设为False,B站真的有过忘续证书的情况
23 | client = blivedm.BLiveClient(room_id, ssl=True)
24 | handler = MyHandler()
25 | client.add_handler(handler)
26 |
27 | client.start()
28 | try:
29 | await client.join()
30 | finally:
31 | await client.stop_and_close()
32 |
33 | # sc 队列
34 | scQue = PriorityQueue(maxsize=0)
35 | # 舰长队列
36 | guardQue = PriorityQueue(maxsize=0)
37 | # 礼物
38 | giftQue = PriorityQueue(maxsize=5)
39 | # 普通弹幕队列
40 | danmuQue = PriorityQueue(maxsize=5)
41 |
42 |
43 | class MyHandler(blivedm.BaseHandler):
44 | async def _on_danmaku(self, client: blivedm.BLiveClient, message: blivedm.DanmakuMessage):
45 | if message.dm_type == 0:
46 | print(f'弹幕:[{client.room_id}] {message.uname}:{message.msg}')
47 | # 权重计算
48 | privilege_type = message.privilege_type
49 | if privilege_type == 0:
50 | privilege_type = 9
51 | rank = (99999-message.user_level*10+(10-privilege_type)
52 | * 10+message.mobile_verify*10)
53 | if danmuQue.full():
54 | danmuQue.get()
55 | danmuQue.put((rank, {"name": message.uname, "type": 'danmu',
56 | 'num': 1, 'action': '说', 'msg': message.msg, 'price': 0}))
57 |
58 | async def _on_gift(self, client: blivedm.BLiveClient, message: blivedm.GiftMessage):
59 | if message.coin_type == 'gold':
60 | print(f'礼物:[{client.room_id}] {message.uname} 赠送{message.gift_name}x{message.num}'
61 | f' ({message.coin_type}瓜子x{message.total_coin})')
62 | price = message.total_coin/1000
63 | if giftQue.full():
64 | giftQue.get()
65 | if price > 1:
66 | giftQue.put((999999-price, {"name": message.uname, "type": 'gift',
67 | 'num': message.num, 'action': message.action, 'msg': '-1', 'price': price}))
68 |
69 | async def _on_buy_guard(self, client: blivedm.BLiveClient, message: blivedm.GuardBuyMessage):
70 | print(f'上舰:[{client.room_id}] {message.username} 购买{message.gift_name}')
71 | guardQue([message.guard_level, {
72 | "name": message.username, "type": 'guard',
73 | 'num': 1, 'action': '上', 'msg': '-1', 'price': message.price/1000}])
74 |
75 | async def _on_super_chat(self, client: blivedm.BLiveClient, message: blivedm.SuperChatMessage):
76 | print(
77 | f'SC:[{client.room_id}] 醒目留言 ¥{message.price} {message.uname}:{message.message}')
78 | # 名称、类型、数量、动作、消息、价格
79 | scQue.put((999999-message.price, {"name": message.uname, "type": 'sc',
80 | 'num': 1, 'action': '发送', 'msg': message.message, 'price': message.price}))
81 |
82 |
83 |
84 |
85 |
86 | if __name__ == '__main__':
87 | asyncio.run(main())
88 |
--------------------------------------------------------------------------------
/testing/filter.py:
--------------------------------------------------------------------------------
1 | from pypinyin import lazy_pinyin
2 |
3 | # 敏感词检测 同音字过滤
4 | f = open(r'sensitive_words.txt', 'r', encoding='utf-8')
5 |
6 | hz = f.readlines()
7 | py = []
8 | for i in range(len(hz)):
9 | hz[i] = hz[i].replace('\n', '')
10 | py.append(str.join('', lazy_pinyin(hz[i])))
11 | # print(hz)
12 | # print(py)
13 |
14 |
15 | readLine = True
16 |
17 |
18 | def filter_text(text):
19 | textPY=str.join('',lazy_pinyin(text))
20 | print(textPY)
21 | for i in range(len(hz)):
22 | if hz[i] in text or py[i] in textPY:
23 | return False
24 | return True
25 |
26 | while readLine:
27 | inputStr = input('请输入:')
28 | if inputStr == 'q':
29 | readLine = False
30 | state = filter_text(inputStr)
31 | print(inputStr+':'+str(state))
32 |
--------------------------------------------------------------------------------
/testing/gpt.py:
--------------------------------------------------------------------------------
1 | import os
2 | import openai
3 |
4 | openai.api_key=''
5 | openai.api_base=''
6 | conversation=[{"role":"system","content":"你是一只会猫猫叫的猫娘,说话要带上喵"},{"role":"user","content":"我的上一句话是什么"}]
7 | response=openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=conversation)
8 | context=response.id
9 | with open('temp.txt', 'a') as a:
10 | a.write('上下文id:'+context+'\n')
11 | a.flush()
12 | print(response.choices[0].message.content)
13 | print(response.usage)
14 |
15 | while True:
16 | str=input("Input Your Question: ")
17 | message=conversation
18 | message.append({"role":"user","content":str})
19 | response=openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=conversation)
20 | print("接收::"+response.choices[0].message.content)
21 | print(response.usage)
22 | print(response.id)
--------------------------------------------------------------------------------
/testing/my_old_thread_main.py:
--------------------------------------------------------------------------------
1 | import openai
2 | import asyncio
3 | import random
4 | import blivedm.blivedm as blivedm
5 | import configparser
6 | from queue import Queue, PriorityQueue
7 | import json
8 | import time
9 | import requests
10 | import os
11 | import _thread
12 | from multiprocessing import Process
13 | import my_vits as vits
14 | import datetime
15 | from playsound import playsound
16 | import xlrd
17 | import xlwt
18 | from xlutils.copy import copy
19 | from pypinyin import lazy_pinyin
20 |
21 |
22 | def write_excel_xls_append(value):
23 | workbook = xlrd.open_workbook(xlslPATH) # 打开工作簿
24 |
25 | sheets = workbook.sheet_names() # 获取工作簿中的所有表格
26 | rows_old = 0
27 | sheetName = str(datetime.date.today())
28 | if sheetName in sheets:
29 | worksheet = workbook.sheet_by_name(sheetName)
30 | rows_old = worksheet.nrows # 获取表格中已存在的数据的行数
31 | new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
32 | if sheetName not in sheets:
33 | new_workbook.add_sheet(sheetName)
34 | new_worksheet = new_workbook.get_sheet(sheetName) # 获取转化后工作簿中的第一个表格
35 | new_worksheet.write(rows_old, 0, value['datetime'])
36 | new_worksheet.write(rows_old, 1, value['user'])
37 | new_worksheet.write(rows_old, 2, value['type'])
38 | new_worksheet.write(rows_old, 3, value['num'])
39 | new_worksheet.write(rows_old, 4, value['action'])
40 | new_worksheet.write(rows_old, 5, value['msg'])
41 | new_worksheet.write(rows_old, 6, value['price'])
42 | new_workbook.save(xlslPATH) # 保存工作簿
43 | if mainConfig['env'] == 'dev':
44 | print("xls格式表格【追加】写入数据成功!")
45 |
46 |
47 | def write_keyboard_text(text):
48 | if mainConfig['env'] == 'dev':
49 | print('vits当前进程id::'+str(os.getpid()))
50 | with open(currTXT, 'w') as w:
51 | w.write('')
52 | w.flush()
53 | with open(currTXT, 'a') as w:
54 | for txt in text:
55 | w.write(txt)
56 | w.flush()
57 |
58 |
59 | def send2gpt(msg):
60 | if mainConfig['env'] == 'dev':
61 | print('gpt当前进程id::'+str(os.getpid()))
62 |
63 | # 向gpt发送消息
64 | sendGptMsg = ''
65 | sendVitsMsg = ''
66 | if msg['type'] == 'danmu':
67 | sendGptMsg = msg['name']+msg['action']+msg['msg']
68 | sendVitsMsg = msg['msg']
69 | elif msg['type'] == 'sc':
70 | sendGptMsg = msg['name']+msg['action']+msg['price']+'块钱sc说'+msg['msg']
71 | sendVitsMsg = sendGptMsg
72 | elif msg['type'] == 'guard':
73 | guardType = '舰长'
74 | if msg['price'] > 200:
75 | guardType = '提督'
76 | elif msg['price'] > 2000:
77 | guardType = '总督'
78 | sendGptMsg = msg['name']+msg['action'] + \
79 | guardType+'了,花了'+msg['price']+'元'
80 | sendVitsMsg = msg['name']+msg['action'] + guardType+'了'
81 | elif msg['type'] == 'gift':
82 | sendGptMsg = msg['name']+msg['action'] + \
83 | msg['msg']+',花了'+msg['price']+'元'
84 | sendVitsMsg = msg['name']+msg['action'] + msg['msg']
85 |
86 | print("向gpt发送::"+sendGptMsg)
87 | # 对话日志 excel
88 | with open('output/'+str(datetime.date.today())+'.txt', 'a') as a:
89 | a.write(str(datetime.datetime.now())+"::发送::"+sendGptMsg+'\n')
90 | a.flush()
91 | write_excel_xls_append({
92 | 'datetime': str(datetime.datetime.now()),
93 | 'user': msg['name'],
94 | 'type': msg['type'],
95 | 'num': msg['num'],
96 | 'action': msg['action'],
97 | 'msg': msg['msg'],
98 | 'price': msg['price']
99 | })
100 |
101 | # 发送给gpt
102 | tempMessage.append({"role": "user", "content": sendGptMsg})
103 | if len(tempMessage) > 3:
104 | del (tempMessage[0])
105 | message = baseContext+tempMessage
106 |
107 | # 接收
108 | response = openai.ChatCompletion.create(
109 | model="gpt-3.5-turbo", messages=message)
110 | responseText = str(response['choices'][0]['message']['content'])
111 | if filter_text(responseText) == False:
112 | return
113 | print("从gpt接收::"+responseText)
114 |
115 | # 生成发送语音
116 | vits.generated_speech(sendVitsMsg, 'sendVits.wav')
117 | # 生成接收语音
118 | vits.generated_speech(responseText, 'recVits.wav')
119 |
120 | playsound('output/sendVits.wav')
121 | time.sleep(0.5)
122 | # 模拟键盘输入
123 | write_keyboard_text(responseText)
124 | playsound('output/recVits.wav')
125 |
126 | # 对话日志
127 | with open('output/'+str(datetime.date.today())+'.txt', 'a') as a:
128 | a.write(str(datetime.datetime.now())+"::接收::"+responseText+'\n')
129 | a.flush()
130 | write_excel_xls_append({
131 | 'datetime': str(datetime.datetime.now()),
132 | 'user': 'gpt35',
133 | 'type': '',
134 | 'num': '',
135 | 'action': '说',
136 | 'msg': responseText,
137 | 'price': 0
138 | })
139 |
140 |
141 | def chatgpt35():
142 | print("运行gpt循环任务")
143 | while True:
144 | chatObj = [0, {"name": '', "type": '', 'num': 0,
145 | 'action': '', 'msg': '', 'price': 0}]
146 | # 从队列获取信息
147 | try:
148 | if topQue.qsize() > 0:
149 | chatObj = topQue.get(True, 1)
150 | elif guardQue.qsize() > 0:
151 | chatObj = guardQue.get(True, 1)
152 | elif giftQue.qsize() > 0:
153 | chatObj = giftQue.get(True, 1)
154 | elif scQue.qsize() > 0:
155 | chatObj = scQue.get(True, 1)
156 | elif danmuQue.qsize() > 0:
157 | chatObj = danmuQue.get(True, 1)
158 | chatObj = chatObj[1]
159 | except:
160 | time.sleep(0)
161 | continue
162 | # 过滤队列
163 | if len(chatObj['name']) > 0:
164 | if filter_text(chatObj['name']) and filter_text(chatObj['msg']):
165 | send2gpt(chatObj)
166 | else:
167 | time.sleep(1)
168 |
169 |
170 | def filter_text(text):
171 | if text == '-1':
172 | return True
173 | textPY = str.join('', lazy_pinyin(text))
174 | for i in range(len(hzSensitiveWord)):
175 | if hzSensitiveWord[i] in text or pySensitiveWord[i] in textPY:
176 | return False
177 | return True
178 |
179 |
180 | async def run_single_client():
181 | # 如果SSL验证失败就把ssl设为False,B站真的有过忘续证书的情况
182 | client = blivedm.BLiveClient(roomID, ssl=True)
183 | handler = MyHandler()
184 | client.add_handler(handler)
185 |
186 | client.start()
187 | try:
188 | await client.join()
189 | finally:
190 | await client.stop_and_close()
191 |
192 |
193 | class MyHandler(blivedm.BaseHandler):
194 | async def _on_danmaku(self, client: blivedm.BLiveClient, message: blivedm.DanmakuMessage):
195 | if message.dm_type == 0:
196 | # print(f'弹幕:[{client.room_id}] {message.uname}:{message.msg}')
197 | # 权重计算
198 | privilege_type = message.privilege_type
199 | if privilege_type == 0:
200 | privilege_type = 9
201 | rank = (99999-message.user_level*10+(10-privilege_type)
202 | * 10+message.mobile_verify*10)
203 | print("rank:"+str(rank)+";name:"+message.uname+";msg:"+message.msg.replace('[', '').replace(']', ''))
204 | danmuQue.put((rank, {'name': message.uname, 'type': 'danmu','num': 1, 'action': '说', 'msg': message.msg.replace('[', '').replace(']', ''), 'price': 0}))
205 |
206 | async def _on_gift(self, client: blivedm.BLiveClient, message: blivedm.GiftMessage):
207 | if message.coin_type == 'gold':
208 | print(f'礼物:[{client.room_id}] {message.uname} 赠送{message.gift_name}x{message.num}'
209 | f' ({message.coin_type}瓜子x{message.total_coin})')
210 | price = message.total_coin/1000
211 | if price > 1:
212 | giftQue.put((999999-price, {"name": message.uname, "type": 'gift',
213 | 'num': message.num, 'action': message.action, 'msg': '-1', 'price': price}))
214 |
215 | async def _on_buy_guard(self, client: blivedm.BLiveClient, message: blivedm.GuardBuyMessage):
216 | print(f'上舰:[{client.room_id}] {message.username} 购买{message.gift_name}')
217 | guardQue((message.guard_level, {
218 | "name": message.username, "type": 'guard',
219 | 'num': 1, 'action': '上', 'msg': '-1', 'price': message.price/1000}))
220 |
221 | async def _on_super_chat(self, client: blivedm.BLiveClient, message: blivedm.SuperChatMessage):
222 | print(
223 | f'SC:[{client.room_id}] 醒目留言 ¥{message.price} {message.uname}:{message.message}')
224 | # 名称、类型、数量、动作、消息、价格
225 | scQue.put((999999-message.price, {"name": message.uname, "type": 'sc',
226 | 'num': 1, 'action': '发送', 'msg': message.message, 'price': message.price}))
227 |
228 | def cleanQue():
229 | while True:
230 | try:
231 | if giftQue.full():
232 | giftQue.get(True, 1)
233 | elif danmuQue.full():
234 | danmuQue.get(True, 1)
235 | except:
236 | print("满了")
237 |
238 | # 配置文件、日志、当前文本、记录excel、敏感词文本
239 | configINI = 'config.ini'
240 | tempTXT = 'output/temp.txt'
241 | currTXT = 'output/currText.txt'
242 | xlslPATH = 'output/record.xlsx'
243 | sensitiveTXT = 'sensitive_words.txt'
244 |
245 | # openai
246 | if os.path.exists('my_config.ini'):
247 | configINI = 'my_config.ini'
248 | con = configparser.ConfigParser()
249 | con.read(configINI, encoding='utf-8')
250 | sections = con.sections()
251 | mainConfig = dict(con.items('main'))
252 | roomID = json.loads(str(requests.get('https://api.live.bilibili.com/room/v1/Room/get_info?room_id=' +
253 | mainConfig['roomid']).content, encoding="utf-8"))['data']['room_id']
254 | openai.api_key = mainConfig['key']
255 | baseContext = [{"role": "system", "content": mainConfig['nya1']}]
256 | response = openai.ChatCompletion.create(
257 | model="gpt-3.5-turbo", messages=baseContext)
258 | time.sleep(1)
259 | print("主线程发送::"+mainConfig['nya1']+"\n主线程接收::" +
260 | str(response['choices'][0]['message']['content']).replace('\r', '').replace('\n', ''))
261 | # 带基础设定最大3条上下文
262 | contextMessage = []
263 | tempMessage = []
264 |
265 | # 敏感词
266 | if os.path.exists('my_sensitive_words.txt'):
267 | sensitiveTXT = 'my_sensitive_words.txt'
268 | sensitiveF = open(sensitiveTXT, 'r', encoding='utf-8')
269 | hzSensitiveWord = sensitiveF.readlines()
270 | pySensitiveWord = []
271 | for i in range(len(hzSensitiveWord)):
272 | hzSensitiveWord[i] = hzSensitiveWord[i].replace('\n', '')
273 | pySensitiveWord.append(str.join('', lazy_pinyin(hzSensitiveWord[i])))
274 |
275 | # 最优先队列、sc、礼物、弹幕队列
276 | topQue = Queue(maxsize=0)
277 | # sc 队列
278 | scQue = PriorityQueue(maxsize=0)
279 | # 舰长队列
280 | guardQue = PriorityQueue(maxsize=0)
281 | # 礼物
282 | giftQue = PriorityQueue(maxsize=5)
283 | # 普通弹幕队列
284 | danmuQue = PriorityQueue(maxsize=10)
285 | topIDs = mainConfig['topid'].split(',')
286 |
287 | # excel数据库
288 | if os.path.exists(xlslPATH) == False:
289 | workbook = xlwt.Workbook()
290 | sheet = workbook.add_sheet("test") # 在工作簿中新建一个表格
291 | workbook.save(xlslPATH)
292 | print("xls格式表格初始化成功!")
293 | print('当前进程id::'+str(os.getpid()))
294 |
295 |
296 | if __name__ == '__main__':
297 | isRun = True
298 | _thread.start_new_thread(cleanQue, ())
299 | _thread.start_new_thread(chatgpt35, ())
300 | _thread.start_new_thread(asyncio.get_event_loop(
301 | ).run_until_complete, (run_single_client(),))
302 | print('All subprocesses start.')
303 | time.sleep(2)
304 | input('input to exit::')
305 | isRun = False
306 | print('All subprocesses done.')
307 |
--------------------------------------------------------------------------------
/testing/my_test_process.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import _thread
3 | import multiprocessing
4 | import time
5 |
6 | def fun1():
7 | while True:
8 | print("fun1")
9 | time.sleep(1)
10 |
11 |
12 | def fun2():
13 | print("fun2")
14 | time.sleep(10)
15 |
16 | def fun3():
17 | while True:
18 | print("fun3")
19 |
20 | p=multiprocessing.Process(target=fun2, args=())
21 | p.start()
22 | _thread.start_new_thread(fun1,())
23 | _thread.start_new_thread(fun3,())
24 | print("end1")
25 | input("input to here .....")
26 | print('end2')
--------------------------------------------------------------------------------
/testing/obsolete_danmu.py:
--------------------------------------------------------------------------------
1 | from bilibili_api import live, sync
2 | import json
3 | import requests
4 |
5 |
6 | env = 'pro' # dev|pro
7 |
8 | roomID = ''
9 | # 获取房间真实 id
10 | room = live.LiveDanmaku(json.loads(str(requests.get('https://api.live.bilibili.com/room/v1/Room/get_info?room_id=' +
11 | roomID).content, encoding="utf-8"))['data']['room_id'])
12 |
13 | @room.on('DANMU_MSG')
14 | async def on_danmaku(event):
15 | print(event)
16 | # 收到弹幕
17 | name = event['data']['info'][2][1]
18 | msg = event['data']['info'][1]
19 | msgs = name+"说:"+msg
20 | msgType = event['data']['info'][0][12]
21 | if env == 'dev':
22 | with open('danmu.txt', 'a') as a:
23 | a.write(str(event)+'\n')
24 | a.flush()
25 | if msgType == 0:
26 | m = 1
27 | print("弹幕::"+msgs)
28 | elif msgType == 1:
29 | print('表情::'+msgs)
30 | else:
31 | print('其他::'+msgs)
32 |
33 | @room.on('SEND_GIFT')
34 | async def on_gift(event):
35 | print(event)
36 | # 收到礼物
37 | if event['data']['data']['batch_combo_send'] is not None:
38 | name = event['data']['data']['batch_combo_send']['uname']
39 | action = event['data']['data']['batch_combo_send']['action']
40 | num = event['data']['data']['batch_combo_send']['gift_num']
41 | gift = event['data']['data']['batch_combo_send']['gift_name']
42 | msgs = name+action+str(num)+'个'+gift
43 | print("礼物::"+msgs)
44 | if env == 'dev':
45 | with open('gift.txt', 'a') as a:
46 | a.write(str(event)+'\n')
47 | a.flush()
48 | if __name__ == '__main__':
49 | sync(room.connect())
50 |
--------------------------------------------------------------------------------
/testing/process.py:
--------------------------------------------------------------------------------
1 | import multiprocessing
2 | from flask import Flask, request
3 | import time
4 |
5 | def func(num):
6 | # 共享数值型变量
7 | # num.value = 2
8 |
9 | # 共享数组型变量
10 | num[2] = 9999
11 |
12 | def rot(num):
13 | app = Flask(__name__)
14 | print("run le")
15 | app.run, ("0.0.0.0", 8081)
16 |
17 | @app.route('/', methods=['GET'])
18 | def put():
19 | return '1'
20 |
21 | if __name__ == '__main__':
22 | # 共享数值型变量
23 | # num = multiprocessing.Value('d', 1)
24 | # print(num.value)
25 |
26 | # 共享数组型变量
27 | num = multiprocessing.Array('i', [1, 2, 3, 4, 5])
28 | print(num[:])
29 |
30 |
31 | p = multiprocessing.Process(target=func, args=(num,))
32 | p.start()
33 | p.join()
34 | p1 = multiprocessing.Process(target=rot, args=(num,))
35 | p1.start()
36 | p1.join
37 |
38 | # 共享数值型变量
39 | # print(num.value)
40 | time.sleep(100)
41 | # 共享数组型变量
42 | print(num[:])
--------------------------------------------------------------------------------
/testing/pth2onnx.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | import torch
5 | from light_cnns import mbv1
6 |
7 | sourcePath='/app/live_vits_chatgpt/models/G_latest.pth'
8 | outPath='/app/live_vits_chatgpt/models/G_latest.onnx'
9 |
10 | def main():
11 | model = mbv1()
12 | imput = torch.randn(1,3,224,224)
13 | torch.onnx.export(model, input, "mobilenetV2.onnx", verbose=True, opset_version=11, export_params=True)
14 |
15 | if __name__ == '__main__':
16 | main()
17 |
18 |
--------------------------------------------------------------------------------
/testing/sensitive_words.txt:
--------------------------------------------------------------------------------
1 | 台湾
2 | 新疆
3 | 北京
4 | 中国
--------------------------------------------------------------------------------
/testing/test1.py:
--------------------------------------------------------------------------------
1 | import test2
2 | import multiprocessing
3 | import time
4 |
5 |
6 | print("主进程")
7 | if __name__ == '__main__':
8 | multiprocessing.freeze_support()
9 |
10 | while True:
11 | p = multiprocessing.Process(target=test2.play)
12 | p.start()
13 | time.sleep(2)
--------------------------------------------------------------------------------
/testing/test2.py:
--------------------------------------------------------------------------------
1 |
2 | print("子进程main外1")
3 |
4 | def play():
5 | print("子进程 函数 3")
6 |
7 | if __name__ == '__main__':
8 | print("子进程main内2")
--------------------------------------------------------------------------------
/testing/testPoolQueeu.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/newreport/vtbai/d5fc86844d36f6dac6068150eb978466e762c23c/testing/testPoolQueeu.py
--------------------------------------------------------------------------------
/testing/testQueue.py:
--------------------------------------------------------------------------------
1 | from queue import Queue, PriorityQueue
2 | import _thread
3 | import datetime
4 | import time
5 |
6 | q=PriorityQueue(maxsize=20)
7 |
8 |
9 | def Put(vau):
10 | while True:
11 | if q.qsize()>10:
12 | print("is full")
13 | try:
14 | q.get(True,1)
15 | except:
16 | q.put(vau,vau)
17 | q.put(vau,vau)
18 | # time.sleep(1)
19 |
20 | def Get():
21 | while True:
22 | str1=q.get()
23 | print(str(datetime.datetime.now())+':'+str(str1))
24 | # time.sleep(1)
25 |
26 | _thread.start_new_thread(Get, ())
27 | _thread.start_new_thread(Put, (2,))
28 | _thread.start_new_thread(Put, (1,))
29 | input()
--------------------------------------------------------------------------------
/tts.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import multiprocessing
3 | import onnxruntime as ort
4 | import torchvision.models as models
5 | from scipy.io import wavfile
6 | import time
7 | import wave
8 | import pyaudio
9 | import os
10 | import sys
11 | import numpy as np
12 | import asyncio
13 | import torch
14 | import uuid
15 | import configparser
16 | sys.path.append('MoeGoe')
17 | import commons as commons
18 | import utils as ttsUtils
19 | from text import text_to_sequence
20 |
21 |
22 | def is_japanese(string):
23 | for ch in string:
24 | if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
25 | return True
26 | return False
27 |
28 |
29 | def is_english(string):
30 | import re
31 | pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
32 | if pattern.fullmatch(string):
33 | return True
34 | else:
35 | return False
36 |
37 |
38 | # 生成/推理语音
39 | def generated_speech(hps, ort_sess, tts_config, text, fileName):
40 | text = f"[ZH]{text}[ZH]"
41 | if is_japanese(text):
42 | text = f"[JA]{text}[JA]"
43 |
44 | # 将文本字符串转换为id
45 | seq = text_to_sequence(text, symbols=hps.symbols,
46 | cleaner_names=hps.data.text_cleaners)
47 | if hps.data.add_blank:
48 | seq = commons.intersperse(seq, 0)
49 | with torch.no_grad():
50 | x = np.array([seq], dtype=np.int64)
51 | x_len = np.array([x.shape[1]], dtype=np.int64)
52 | sid = tts_config['speaker_id']
53 | sid = np.array([sid], dtype=np.int64)
54 | scales = np.array([tts_config['noise_scale'], tts_config['noise_scale_w'],
55 | tts_config['length_scale']], dtype=np.float32)
56 | scales.resize(1, 3)
57 | ort_inputs = {
58 | 'input': x,
59 | 'input_lengths': x_len,
60 | 'scales': scales,
61 | 'sid': sid
62 | }
63 | t1 = time.time()
64 | audio = np.squeeze(ort_sess.run(None, ort_inputs))
65 | audio *= 32767.0 / max(0.01, np.max(np.abs(audio))) * 0.6
66 | audio = np.clip(audio, -32767.0, 32767.0)
67 | t2 = time.time()
68 | spending_time = "推理时间:"+str(t2-t1)+"s"
69 | print(spending_time+" 推理内容:"+text)
70 | wavfile.write('output/wav/'+fileName+'.wav', hps.data.sampling_rate,
71 | audio.astype(np.int16))
72 |
73 | # 播放语音和更改文字
74 |
75 |
76 | def play(is_run, tts_config, wav_que, curr_txt):
77 | print("运行play子进程")
78 | is_auto_del = bool(int(tts_config['auto_del_wav']))
79 | while is_run:
80 | # 阻塞
81 | text = wav_que.get()
82 | print("开始播放内容::"+text)
83 | name = text.split("::")[0]
84 | txt = text.split("::")[1]
85 | p = multiprocessing.Process(
86 | target=change_txt, args=(tts_config, txt, curr_txt))
87 | p.start()
88 | play_audio('output/wav/'+name+'.wav')
89 | if is_auto_del:
90 | os.remove('output/wav/'+name+'.wav')
91 | time.sleep(0.5)
92 | p.join()
93 |
94 | def change_txt(tts_config, text, curr_txt):
95 | # print("改变文字"+text)
96 | curr_txt.value = ''
97 | for txt in text:
98 | curr_txt.value = curr_txt.value + txt
99 | # print(curr_txt.value)
100 | time.sleep(float(tts_config['interval_ms'])/1000)
101 |
102 | def play_audio(file_path):
103 | CHUNK = 1024
104 | wf = wave.open(file_path, 'rb')
105 | p = pyaudio.PyAudio()
106 | stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
107 | channels=wf.getnchannels(),
108 | rate=wf.getframerate(),
109 | output=True)
110 |
111 | data = wf.readframes(CHUNK)
112 |
113 | while data:
114 | stream.write(data)
115 | data = wf.readframes(CHUNK)
116 |
117 | stream.stop_stream()
118 | stream.close()
119 |
120 | p.terminate()
121 |
122 |
123 |
124 | def inference(is_run, tts_config, ttsQue, wav_que):
125 | print("运行tts子进程")
126 | config_ini = 'config/config.ini'
127 | if os.path.exists('config/my_config.ini'):
128 | config_ini = 'config/my_config.ini'
129 | con = configparser.ConfigParser()
130 | con.read(config_ini, encoding='utf-8')
131 | tts_config = dict(con.items('tts'))
132 |
133 | hps = ttsUtils.get_hparams_from_file(tts_config['model_config'])
134 | ort_sess = ort.InferenceSession(tts_config['model_onnx'])
135 |
136 | while is_run:
137 | # 阻塞
138 | text = ttsQue.get()
139 | name = str(uuid.uuid1())
140 | print("生成语音::"+name+"::"+text)
141 | generated_speech(hps, ort_sess, tts_config, text,name)
142 | wav_que.put(name+"::"+text)
143 |
144 | if __name__ == '__main__':
145 | config_ini = 'config/config.ini'
146 | if os.path.exists('config/my_config.ini'):
147 | config_ini = 'config/my_config.ini'
148 | con = configparser.ConfigParser()
149 | con.read(config_ini, encoding='utf-8')
150 | tts_config = dict(con.items('tts'))
151 |
152 | hps = ttsUtils.get_hparams_from_file(tts_config['model_config'])
153 | ort_sess = ort.InferenceSession(tts_config['model_onnx'])
154 |
155 | str1 = "最喜欢的季节是春天。我觉得春天是一个充满生机和活力的季节。随着百花的盛开,春天带来了新的生命和希望。在春天,气温逐渐升高,天气也变得温暖和宜人。大自然开始苏醒,鸟儿唧唧喳喳地叫着,树木渐渐发芽,花儿绽放出五彩斑斓的色彩。春天也是一个让人感到愉快的季节。人们开始换上轻便的衣服,走出户外,感受大自然的美妙。我喜欢在春天里去公园散步,享受春风拂面的感觉。在公园里,可以看到满眼的绿意和各种各样的鲜花,让人心情舒畅。此外,春天也是一个让人充满期待和希望的季节。在新的一年里,一切都是全新的开始。人们开始规划新的计划和目标,并努力实现它们。总之,对我来说,春天是一个非常特别的季节。它带给我无尽的欢乐和动力,让我感到充满希望和激情。我相信,在这个美好的季节里,我们可以收获更多的爱与快乐。"
156 | generated_speech(hps, ort_sess, tts_config, str1, 'temp1')
157 |
--------------------------------------------------------------------------------