├── LICENSE
├── README.md
├── README_en.md
├── SIMPLIFICADA_ViralCutter.ipynb
├── ViralCutter.ipynb
├── i18n
├── i18n.py
├── locale
│ ├── en_US.json
│ └── pt_BR.json
├── locale_diff.py
└── scan_i18n.py
├── main.py
└── scripts
├── adjust_subtitles.py
├── burn_subtitles.py
├── create_viral_segments.py
├── cut_segments.py
├── download_video.py
├── edit_video.py
├── one_face.py
├── save_json.py
├── transcribe_cuts.py
├── transcribe_video.py
└── two_face.py
/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 | # ViralCutter: Gerador de Vídeos Virais
2 | [  ](https://discord.gg/aihubbrasil)
3 | [English](https://github.com/RafaelGodoyEbert/ViralCutter/blob/main/README_en.md) | [Português](https://github.com/RafaelGodoyEbert/ViralCutter/blob/main/README.md)
4 |
5 | ## **Descrição**
6 | ViralCutter é uma ferramenta inovadora para gerar vídeos virais a partir de conteúdo existente. Com técnicas avançadas de processamento de vídeo e áudio, o ViralCutter corta e edita segmentos de vídeo que são perfeitos para compartilhamento em redes sociais. Utilizando o modelo WhisperX para transcrição e geração de legendas automáticas, ele adapta os vídeos para o formato 9:16 (vertical), ideal para plataformas como TikTok e Instagram com Reels e Youtube com Shorts.
7 |
8 | ## **Funcionalidades**
9 |
10 | - **Download de Vídeos**: Baixa vídeos do YouTube através de uma URL fornecida.
11 | - **Transcrição de Áudio**: Converte áudio em texto utilizando o modelo WhisperX.
12 | - **Identificação de Segmentos Virais**: Utiliza IA para detectar partes do vídeo com alto potencial de viralização.
13 | - **Corte e Ajuste de Formato**: Corta os segmentos selecionados e ajusta a proporção para 9:16.
14 | - **Mesclagem de Áudio e Vídeo**: Combina o áudio transcrito com os clipes de vídeo processados.
15 | - **Exportação em Lote**: Gera um arquivo ZIP com todos os vídeos virais criados, facilitando o download e compartilhamento.
16 | - **Legenda personalizada**: Você cria uma legenda personalizada com cores, highlight, sem highlight ou palavra por palavra, tendo uma ampla possibilidade de edição.
17 |
18 | ## **Como Usar**
19 |
23 | - Entre no link e siga os passos na ordem: [](https://colab.research.google.com/drive/1UZKzeqjIeEyvq9nPx7s_4mU6xlkZQn_R?usp=sharing#scrollTo=pa36OeArowme)
24 | - Versão simplificada sem opção de mudança de texto [](https://colab.research.google.com/drive/1aDNLtoJZa9Z0lKcYTR6CGNMgZ_iTpwJD?usp=sharing)
25 | - Criei esse site para ajudar a dividir a trascrição, já que ChatGPT tem limites: [Split text for ChatGPT](https://rafaelgodoyebert.github.io/ViralCutter/)
26 |
27 | ## **Limitações**
28 |
29 | - O tempo de processamento pode ser elevado para vídeos longos.
30 | - A qualidade dos vídeos gerados pode variar com base na qualidade do vídeo original.
31 |
32 | ## Inspiração:
33 | Este projeto foi inspirado nos seguintes repositórios:
34 |
35 | * [Reels Clips Automator](https://github.com/eddieoz/reels-clips-automator)
36 | * [YoutubeVideoToAIPoweredShorts](https://github.com/Fitsbit/YoutubeVideoToAIPoweredShorts)
37 |
38 | ## TODO📝
39 | - [x] Release code
40 | - [ ] Huggingface SpaceDemo
41 | - [x] Two face in the cut
42 | - [x] Custom caption and burn
43 | - [x] Make the code faster
44 | - [ ] More types of framing beyond 9:16
45 | - [x] The cut follows the face as it moves
46 | - [ ] Automatic translation
47 | - [ ] Satisfactory video on the side
48 | - [ ] Background music
49 | - [ ] watermark at user's choice
50 | - [ ] Upload directly to YouTube channel
51 |
52 | ## Exemplos
53 | ### Exmplo de vídeo viral ``com highlight ativo`` [comprimido pra caber no github]
54 | https://github.com/user-attachments/assets/dd9a7039-e0f3-427a-a6e1-f50ab5029082
55 |
56 | ### Exemplo Opus Clip vs ViralCutter [comprimido pra caber no github]
57 | https://github.com/user-attachments/assets/12916792-dc0e-4f63-a76b-5698946f50f4
58 |
59 | ### Exemplo 2 faces [comprimido pra caber no github]
60 | https://github.com/user-attachments/assets/ca7ebb9c-52ba-4171-a513-625bef690a2b
61 |
62 | ## **Contribuições**
63 | Quer ajudar a tornar o ViralCutter ainda melhor? Se você tiver sugestões ou quiser contribuir com o código, fique à vontade para abrir uma issue ou enviar um pull request no nosso repositório do GitHub.
64 |
65 | ## **Versão**
66 | `0.6v Alpha`
67 | Uma alternativa gratuita ao `opus.pro` e ao `vidyo.ai`.
68 |
69 | ---
70 |
--------------------------------------------------------------------------------
/README_en.md:
--------------------------------------------------------------------------------
1 | # ViralCutter: Viral Video Generator
2 | [  ](https://discord.gg/aihubbrasil)
3 | [English](https://github.com/RafaelGodoyEbert/ViralCutter/blob/main/README_en.md) | [Português](https://github.com/RafaelGodoyEbert/ViralCutter/blob/main/README.md)
4 |
5 | ## **Description**
6 | ViralCutter is an innovative tool for generating viral videos from existing content. With advanced video and audio processing techniques, ViralCutter cuts and edits video segments that are perfect for sharing on social media. Using the WhisperX model for transcription and automatic subtitle generation, it adapts videos to a 9:16 (vertical) format, ideal for platforms like TikTok and Instagram Reels, as well as YouTube Shorts.
7 |
8 | ## **Features**
9 |
10 | - **Video Download**: Downloads videos from YouTube using a provided URL.
11 | - **Audio Transcription**: Converts audio to text using the WhisperX model.
12 | - **Viral Segment Identification**: Uses AI to detect parts of the video with high viral potential.
13 | - **Cutting and Format Adjustment**: Cuts selected segments and adjusts the aspect ratio to 9:16.
14 | - **Audio and Video Merging**: Combines transcribed audio with processed video clips.
15 | - **Batch Export**: Generates a ZIP file with all created viral videos, making it easy to download and share.
16 | - **Custom Subtitles**: Create personalized subtitles with options for color, highlighting, or word-by-word display, allowing for extensive editing possibilities.
17 |
18 | ## **How to Use**
19 | - Go to the link and follow the steps in order: [](https://colab.research.google.com/drive/1UZKzeqjIeEyvq9nPx7s_4mU6xlkZQn_R?usp=sharing#scrollTo=pa36OeArowme) (only Portuguese)
20 | - Simplified version without text change options [](https://colab.research.google.com/drive/1aDNLtoJZa9Z0lKcYTR6CGNMgZ_iTpwJD?usp=sharing) (only Portuguese)
21 | - I created this site to help split the transcription, since ChatGPT has limits: [Split text for ChatGPT](https://rafaelgodoyebert.github.io/ViralCutter/)
22 |
23 | ## **Limitations**
24 |
25 | - Processing time may be high for long videos.
26 | - The quality of generated videos may vary based on the quality of the original video.
27 |
28 | ## Inspiration:
29 | This project was inspired by the following repositories:
30 |
31 | * [Reels Clips Automator](https://github.com/eddieoz/reels-clips-automator)
32 | * [YoutubeVideoToAIPoweredShorts](https://github.com/Fitsbit/YoutubeVideoToAIPoweredShorts)
33 |
34 | ## TODO📝
35 | - [x] Release code
36 | - [ ] Hugging Face Space Demo
37 | - [x] Two faces in the cut
38 | - [x] Custom caption and burn
39 | - [x] Make the code faster
40 | - [ ] More types of framing beyond 9:16
41 | - [x] The cut follows the face as it moves
42 | - [ ] Automatic translation
43 | - [ ] Satisfactory video on the side
44 | - [ ] Background music
45 | - [ ] Watermark at user's choice
46 | - [ ] Upload directly to YouTube channel
47 |
48 | ## Example of viral video ``with highlight active``
49 | https://github.com/user-attachments/assets/dd9a7039-e0f3-427a-a6e1-f50ab5029082
50 |
51 | ## **Contributions**
52 | Want to help make ViralCutter even better? If you have suggestions or want to contribute code, feel free to open an issue or send a pull request in our GitHub repository.
53 |
54 | ## **Version**
55 | `0.6v Alpha`
56 | A free alternative to `opus.pro` and `vidyo.ai`.
57 |
58 | ---
--------------------------------------------------------------------------------
/SIMPLIFICADA_ViralCutter.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "source": [
6 | "# ViralCutter\n",
7 | "Uma alternativa gratuita ao `opus.pro` e ao `vidyo.ai`\n",
8 | "\n",
9 | "## ⚠️Você está na versão SIMPLIFICADA , se quiser mais modificações para o texto, entre na versão completa no link abaixo.\n",
10 | "https://colab.research.google.com/drive/1UZKzeqjIeEyvq9nPx7s_4mU6xlkZQn_R?usp=sharing#scrollTo=6Q-ljfsw1unE"
11 | ],
12 | "metadata": {
13 | "id": "pa36OeArowme"
14 | }
15 | },
16 | {
17 | "cell_type": "markdown",
18 | "source": [
19 | "# Suporte em:\n",
20 | "[  ](https://discord.gg/aihubbrasil)"
21 | ],
22 | "metadata": {
23 | "id": "6Q-ljfsw1unE"
24 | }
25 | },
26 | {
27 | "cell_type": "code",
28 | "source": [
29 | "#@title Áudio Mudo\n",
30 | "%%html\n",
31 | ""
32 | ],
33 | "metadata": {
34 | "cellView": "form",
35 | "colab": {
36 | "base_uri": "https://localhost:8080/",
37 | "height": 93
38 | },
39 | "id": "-ry4FVGroylp",
40 | "outputId": "9084b31f-9b46-404a-e908-f92d28a744f7"
41 | },
42 | "execution_count": null,
43 | "outputs": [
44 | {
45 | "output_type": "display_data",
46 | "data": {
47 | "text/plain": [
48 | ""
49 | ],
50 | "text/html": [
51 | "\n"
52 | ]
53 | },
54 | "metadata": {}
55 | }
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": null,
61 | "metadata": {
62 | "cellView": "form",
63 | "id": "e76jiRnjONmj",
64 | "colab": {
65 | "base_uri": "https://localhost:8080/"
66 | },
67 | "outputId": "122bb7b6-efcc-497c-e74b-853c7f7329e1"
68 | },
69 | "outputs": [
70 | {
71 | "output_type": "stream",
72 | "name": "stdout",
73 | "text": [
74 | "Finalizado...\n"
75 | ]
76 | }
77 | ],
78 | "source": [
79 | "#@title Dependência\n",
80 | "from IPython.display import clear_output\n",
81 | "!git clone https://github.com/RafaelGodoyEbert/ViralCutter.git\n",
82 | "!pip install -U g4f[all] -q\n",
83 | "!pip install yt_dlp -q\n",
84 | "!pip install ffmpeg-python -q\n",
85 | "!pip install git+https://github.com/m-bain/whisperx.git -q\n",
86 | "!pip install mediapipe -q\n",
87 | "%cd /content/ViralCutter\n",
88 | "clear_output()\n",
89 | "print(\"Finalizado...\")"
90 | ]
91 | },
92 | {
93 | "cell_type": "code",
94 | "source": [
95 | "#@title Configuração (Antes de executar, configure)\n",
96 | "import os\n",
97 | "from scripts import download_video, transcribe_video, create_viral_segments, cut_segments, edit_video, transcribe_cuts, adjust_subtitles, burn_subtitles, save_json\n",
98 | "from IPython.display import clear_output\n",
99 | "\n",
100 | "# Create necessary directories\n",
101 | "os.makedirs('tmp', exist_ok=True)\n",
102 | "os.makedirs('final', exist_ok=True)\n",
103 | "os.makedirs('subs', exist_ok=True)\n",
104 | "os.makedirs('subs_ass', exist_ok=True)\n",
105 | "os.makedirs('burned_sub', exist_ok=True)\n",
106 | "\n",
107 | "# Cores originais invertidas\n",
108 | "vermelho = \"0A08E4\"\n",
109 | "amarelo = \"00FFFF\"\n",
110 | "azul = \"700206\"\n",
111 | "preto = \"000000\"\n",
112 | "verde = \"58DA7D\"\n",
113 | "branco = \"FFFFFF\"\n",
114 | "laranja = \"0099FE\"\n",
115 | "roxo = \"800080\"\n",
116 | "rosa = \"C77DF9\"\n",
117 | "ciano = \"FFFF00\"\n",
118 | "marrom = \"2D4A8C\"\n",
119 | "cinza = \"808080\"\n",
120 | "verde_limao = \"32CD32\"\n",
121 | "azul_claro = \"E6D8AD\"\n",
122 | "verde = \"0FF00\"\n",
123 | "\n",
124 | "#@ Se quiser pular apenas para a parte de refazer a edição as legendas, ative-o\n",
125 | "# Burn subtitles option\n",
126 | "burn_only = False #@{type:\"boolean\"}\n",
127 | "\n",
128 | "#@ ---\n",
129 | "#@markdown 🎬 Configurações do Vídeo 🎬 \n",
130 | "\n",
131 | "#@markdown ---\n",
132 | "#@markdown 🔗 Link do vídeo no YouTube \n",
133 | "url = 'https://youtu.be/1ZnwqFh3CrA?si=zpSig52k11NY7que' # @param {type: \"string\"}\n",
134 | "#@ ---\n",
135 | "#@markdown 📊 Quantidade de cortes \n",
136 | "num_segments = 3 # @param {type:\"number\"}\n",
137 | "#@ ---\n",
138 | "#@ 🌟 Modo viral \n",
139 | "viral_mode = True #@{type:\"boolean\"}\n",
140 | "#@ ---\n",
141 | "#@ 🔤 Legendas queimadas \n",
142 | "burn_subtitles_option = True # @ [\"False\", \"True\"] {type:\"raw\"}\n",
143 | "#@ ---\n",
144 | "#@ 🎨 Tema personalizado (caso não use modo viral) \n",
145 | "themes = '' # @ {type:\"string\", placeholder:\"Se `viral_mode` desmarcado, coloque o tema aqui, se mais que um, separado por virgulas\"}\n",
146 | "#@ ---\n",
147 | "#@ 🧠 Modelo para análise de vídeo \n",
148 | "model = 'large-v3' # @ ['base', 'large-v3']\n",
149 | "\n",
150 | "#@markdown \n",
151 | "#@markdown ⏳ Configurações de Tempo ⏳ \n",
152 | "\n",
153 | "#@markdown ---\n",
154 | "#@markdown ⌛ Tempo mínimo (segundos) \n",
155 | "tempo_minimo = 15 #@param{type: \"number\"}\n",
156 | "#@ ---\n",
157 | "#@markdown ⏳ Tempo máximo (segundos) \n",
158 | "tempo_maximo = 90 #@param{type: \"number\"}\n",
159 | "\n",
160 | "#@markdown \n",
161 | "#@markdown 💬 Configurações de Legendas 💬 \n",
162 | "# ⚠️ Só mexa se ``burn_subtitles_option`` estiver ativo! \n",
163 | "\n",
164 | "#@markdown ---\n",
165 | "#@ ### Fonte da legenda\n",
166 | "fonte = \"Arial\" #@{type: \"string\"}\n",
167 | "#@ ---\n",
168 | "#@ ### Tamanho da fonte\n",
169 | "base_size = 12 #@{type: \"number\"}\n",
170 | "#@ ---\n",
171 | "#@ ### Cor da fonte\n",
172 | "base_color_c = \"FFFFFF\" #@{type: \"string\"}\n",
173 | "#@ ---\n",
174 | "#@ ### Transparência da fonte (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
175 | "base_color_t = \"00\" #@{type: \"string\"}\n",
176 | "base_color = f\"&H{base_color_t}\" + base_color_c + \"&\"\n",
177 | "\n",
178 | "#@ ---\n",
179 | "#@ ### Cor do contorno\n",
180 | "contorno_c = \"808080\" #@{type: \"string\"}\n",
181 | "#@ ---\n",
182 | "#@ ### Transparência da fonte (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
183 | "contorno_t = \"00\" #@{type: \"string\"}\n",
184 | "contorno = f\"&H{contorno_t}\" + contorno_c + \"&\"\n",
185 | "\n",
186 | "#@ ---\n",
187 | "#@ ### Tamanho do highlight\n",
188 | "h_size = 14 #@{type: \"number\"}\n",
189 | "\n",
190 | "#@ ---\n",
191 | "#@ ### Número de palavras por bloco\n",
192 | "palavras_por_bloco = 5 #@{type: \"number\"}\n",
193 | "\n",
194 | "#@ ---\n",
195 | "#@ ### Limite de gap entre falas (em segundos)\n",
196 | "limite_gap = 0.5 #@{type: \"number\"}\n",
197 | "\n",
198 | "#@ ---\n",
199 | "#@markdown ### Modo de exibição das legendas (highlight é palavra em destaque)\n",
200 | "modo = 'highlight' # @param ['highlight', 'sem_higlight', 'palavra_por_palavra']\n",
201 | "\n",
202 | "#@ ---\n",
203 | "#@ 🎨 Configurações do Destaque \n",
204 | "\n",
205 | "#@ ---\n",
206 | "#@ ### Cor da fonte de destaque\n",
207 | "highlight_color_c = \"0FF00\" #@{type: \"string\"}\n",
208 | "#@ ---\n",
209 | "#@ ### Transparência da fonte de destaque (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
210 | "highlight_color_t = \"00\" #@{type: \"string\"}\n",
211 | "highlight_color = f\"&H{highlight_color_t}\" + highlight_color_c + \"&\"\n",
212 | "\n",
213 | "#@ ---\n",
214 | "#@ ### Posição vertical da legenda (1=170, 2=130, 3=99, 4=60 (default), 5=20)\n",
215 | "posicao_vertical = 60 #@{type: \"number\"}\n",
216 | "\n",
217 | "#@ ---\n",
218 | "#@ ### Cor da sombra\n",
219 | "cor_da_sombra_c = \"000000\" #@{type: \"string\"}\n",
220 | "#@ ---\n",
221 | "#@ ### Transparência da fonte (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
222 | "cor_da_sombra_t = \"00\" #@{type: \"string\"}\n",
223 | "cor_da_sombra = f\"&H{cor_da_sombra_t}\" + cor_da_sombra_c + \"&\"\n",
224 | "\n",
225 | "#@ ---\n",
226 | "#@ ### Alinhamento do texto\n",
227 | "#@ 1 = Esquerda, 2 = Centro (default), 3 = Direita\n",
228 | "alinhamento = 2 #@{type: \"slider\", min: 1, max: 3}\n",
229 | "\n",
230 | "#@ ---\n",
231 | "#@ ### Efeitos no texto\n",
232 | "negrito = 0 #@{type: \"number\"}\n",
233 | "italico = 0 #@{type: \"number\"}\n",
234 | "sublinhado = 0 #@{type: \"number\"}\n",
235 | "tachado = 0 #@{type: \"number\"}\n",
236 | "\n",
237 | "#@ ---\n",
238 | "#@markdown ### Estilo da borda | 1 = Contorno, 3 = Caixa\n",
239 | "#@\n",
240 | "estilo_da_borda = 1 #@param {type: \"number\"}\n",
241 | "\n",
242 | "#@ ---\n",
243 | "#@ ### Espessura do contorno\n",
244 | "espessura_do_contorno = 1.5 #@{type: \"number\"}\n",
245 | "\n",
246 | "#@ ---\n",
247 | "#@ ### Tamanho da sombra\n",
248 | "tamanho_da_sombra = 10 #@{type: \"number\"}\n",
249 | "\n",
250 | "if burn_only:\n",
251 | " print(\"Burn only mode activated. Skipping to subtitle burning...\")\n",
252 | " burn_subtitles.burn()\n",
253 | " print(\"Subtitle burning completed.\")\n",
254 | "else:\n",
255 | " # Execute the pipeline\n",
256 | " input_video = download_video.download(url)\n",
257 | " srt_file, tsv_file = transcribe_video.transcribe(input_video, model)\n",
258 | " clear_output()\n",
259 | " viral_segments = create_viral_segments.create(num_segments, viral_mode, themes, tempo_minimo, tempo_maximo)\n",
260 | " save_json.save_viral_segments(viral_segments)\n",
261 | "\n",
262 | " cut_segments.cut(viral_segments)\n",
263 | " edit_video.edit()\n",
264 | "\n",
265 | " if burn_subtitles_option:\n",
266 | " import subprocess\n",
267 | " def transcribe():\n",
268 | " def generate_whisperx(input_file, output_folder, model=model):\n",
269 | " output_file = os.path.join(output_folder, f\"{os.path.splitext(os.path.basename(input_file))[0]}.srt\")\n",
270 | " json_file = os.path.join(output_folder, f\"{os.path.splitext(os.path.basename(input_file))[0]}.json\") # Define the JSON output file\n",
271 | "\n",
272 | " # Skip processing if the JSON file already exists\n",
273 | " if os.path.exists(json_file):\n",
274 | " print(f\"Arquivo já existe, pulando: {json_file}\")\n",
275 | " return\n",
276 | "\n",
277 | " command = f\"\"\"\n",
278 | " whisperx {input_file} \\\n",
279 | " --model {model} \\\n",
280 | " --task transcribe \\\n",
281 | " --align_model WAV2VEC2_ASR_LARGE_LV60K_960H \\\n",
282 | " --chunk_size 10 \\\n",
283 | " --vad_onset 0.4 \\\n",
284 | " --vad_offset 0.3 \\\n",
285 | " --compute_type float32 \\\n",
286 | " --batch_size 10 \\\n",
287 | " --output_dir {output_folder} \\\n",
288 | " --output_format srt \\\n",
289 | " --output_format json \\\n",
290 | " \"\"\"\n",
291 | "\n",
292 | " print(f\"Transcrevendo: {input_file}...\")\n",
293 | " result = subprocess.run(command, shell=True, text=True, capture_output=True)\n",
294 | " print(f\"Comando executado: {command}\")\n",
295 | "\n",
296 | " if result.returncode != 0:\n",
297 | " print(\"Erro durante a transcrição:\")\n",
298 | " print(result.stderr)\n",
299 | " else:\n",
300 | " print(f\"Transcrição concluída. Arquivo salvo em: {output_file} e {json_file}\")\n",
301 | " print(result.stdout) # Verificar a saída correta\n",
302 | "\n",
303 | " # Define o diretório de entrada e o diretório de saída\n",
304 | " input_folder = '/content/ViralCutter/final'\n",
305 | " output_folder = '/content/ViralCutter/subs'\n",
306 | "\n",
307 | " # Itera sobre todos os arquivos na pasta de entrada\n",
308 | " for filename in os.listdir(input_folder):\n",
309 | " if filename.endswith('.mp4'): # Filtra apenas arquivos .mp4\n",
310 | " input_file = os.path.join(input_folder, filename)\n",
311 | " generate_whisperx(input_file, output_folder)\n",
312 | "\n",
313 | " transcribe()\n",
314 | " adjust_subtitles.adjust(base_color, base_size, h_size, highlight_color, palavras_por_bloco, limite_gap, modo, posicao_vertical, alinhamento, fonte, contorno, cor_da_sombra, negrito, italico, sublinhado, tachado, estilo_da_borda, espessura_do_contorno, tamanho_da_sombra)\n",
315 | " burn_subtitles.burn() # Queimar legendas\n",
316 | " else:\n",
317 | " print(\"Subtitle burning skipped.\")\n",
318 | "\n",
319 | " print(\"Process completed successfully!\")"
320 | ],
321 | "metadata": {
322 | "cellView": "form",
323 | "id": "DNn8ZKJdD5XG"
324 | },
325 | "execution_count": null,
326 | "outputs": []
327 | },
328 | {
329 | "cell_type": "markdown",
330 | "source": [
331 | "Exemplo de resposta "
332 | ],
333 | "metadata": {
334 | "id": "WYquVNzP0FhO"
335 | }
336 | },
337 | {
338 | "cell_type": "code",
339 | "source": [
340 | "#@title Virais criado\n",
341 | "#@markdown Irá imprimir ``Segmento 0:``, cada número representa um vídeo para colocar na célula posterior.\n",
342 | "import json\n",
343 | "\n",
344 | "# Lê o conteúdo do arquivo viral_segments.txt\n",
345 | "with open('/content/ViralCutter/tmp/viral_segments.txt', 'r', encoding='utf-8') as file:\n",
346 | " data = json.load(file)\n",
347 | "\n",
348 | "# Itera sobre os segmentos e imprime as informações desejadas\n",
349 | "for index, segment in enumerate(data['segments']):\n",
350 | " title = segment['title']\n",
351 | " description = segment['description']\n",
352 | " score = segment['score']\n",
353 | " print(f\"Segmento {index}:\")\n",
354 | " print(f\" Título: {title}\")\n",
355 | " print(f\" Descrição: {description}\")\n",
356 | " print(f\" Score: {score}\")\n",
357 | " print()\n"
358 | ],
359 | "metadata": {
360 | "colab": {
361 | "base_uri": "https://localhost:8080/"
362 | },
363 | "cellView": "form",
364 | "id": "CH1S792_3l5q",
365 | "outputId": "634c2e33-31b7-451e-dbd2-587c06f7a1fb"
366 | },
367 | "execution_count": null,
368 | "outputs": [
369 | {
370 | "output_type": "stream",
371 | "name": "stdout",
372 | "text": [
373 | "Segmento 0:\n",
374 | " Título: Descomplicando a Vida: Menos é Mais\n",
375 | " Descrição: Discussão sobre a ideia de que estar ocupado não é uma medalha de honra e que ter tempo é um verdadeiro indicador de sucesso.\n",
376 | " Score: 85\n",
377 | "\n",
378 | "Segmento 1:\n",
379 | " Título: A Realidade do Tempo e das Tarefas\n",
380 | " Descrição: Reflexão sobre a importância de estar presente em cada momento e não se deixar levar pela pressão de fazer tudo ao mesmo tempo.\n",
381 | " Score: 90\n",
382 | "\n",
383 | "Segmento 2:\n",
384 | " Título: Aprendendo a Dizer Não\n",
385 | " Descrição: A importância de aprender a dizer não para priorizar o que realmente importa na vida, destacando o respeito próprio.\n",
386 | " Score: 80\n",
387 | "\n"
388 | ]
389 | }
390 | ]
391 | },
392 | {
393 | "cell_type": "markdown",
394 | "source": [
395 | "# Resultado em vídeo"
396 | ],
397 | "metadata": {
398 | "id": "QWVaFdjIGY4i"
399 | }
400 | },
401 | {
402 | "cell_type": "code",
403 | "execution_count": null,
404 | "metadata": {
405 | "id": "y3kiEMLqoHJ7",
406 | "cellView": "form"
407 | },
408 | "outputs": [],
409 | "source": [
410 | "#@title Resultado em vídeo\n",
411 | "#@markdown Escolha o número do vídeo\n",
412 | "from IPython.display import HTML\n",
413 | "from base64 import b64encode\n",
414 | "import json\n",
415 | "\n",
416 | "numero_do_video = 1 #@param {type:\"number\"}\n",
417 | "tipo_de_video = \"Legendas queimadas\" # [\"Legendas queimadas\", \"Video limpo\"]\n",
418 | "\n",
419 | "if tipo_de_video == \"Legendas queimadas\":\n",
420 | " pasta_video = 'burned_sub'\n",
421 | " sufix = 'processed_subtitled' #final-output000_\n",
422 | "else:\n",
423 | " pasta_video = 'final'\n",
424 | " sufix = 'processed'\n",
425 | "\n",
426 | "def show_video(video_path, video_width=400):\n",
427 | " video_file = open(video_path, \"r+b\").read()\n",
428 | " video_url = f\"data:video/mp4;base64,{b64encode(video_file).decode()}\"\n",
429 | " return HTML(f\"\"\" \"\"\")\n",
430 | "\n",
431 | "# Load segment information from the text file\n",
432 | "with open('/content/ViralCutter/tmp/viral_segments.txt', 'r') as file:\n",
433 | " segments_data = json.load(file)\n",
434 | "\n",
435 | "# Função para exibir o vídeo e as informações correspondentes ao índice\n",
436 | "def display_video_with_segment(index):\n",
437 | " try:\n",
438 | " segment = segments_data['segments'][index]\n",
439 | "\n",
440 | " # Print Title, Description, and Score of the segment\n",
441 | " print(f\"Título: {segment['title']}\")\n",
442 | " print(f\"Descrição: {segment['description']}\")\n",
443 | " print(f\"Score: {segment['score']}\")\n",
444 | " print()\n",
445 | "\n",
446 | " # Input video\n",
447 | " video_path = f'/content/ViralCutter/{pasta_video}/final-output{str(index).zfill(3)}_{sufix}.mp4'\n",
448 | " return show_video(video_path)\n",
449 | "\n",
450 | " except IndexError:\n",
451 | " print(f\"Segmento não encontrado para o índice {index}\")\n",
452 | " return None\n",
453 | "\n",
454 | "# Exibir vídeo e informações do segmento correspondente ao índice 0 (por exemplo)\n",
455 | "display_video_with_segment(numero_do_video) # Substitua o índice conforme necessário\n"
456 | ]
457 | },
458 | {
459 | "cell_type": "markdown",
460 | "source": [
461 | "# BAIXAR EM ZIP"
462 | ],
463 | "metadata": {
464 | "id": "JXEYU0p6li2G"
465 | }
466 | },
467 | {
468 | "cell_type": "code",
469 | "source": [
470 | "#@title Baixar somente Cortes com resolução original 💻\n",
471 | "#@markdown Logo vai baixar os vídeos que são somente os cortes, sem a edição e foco no rosto\n",
472 | "import os\n",
473 | "import zipfile\n",
474 | "\n",
475 | "# Definir o diretório onde os vídeos estão localizados\n",
476 | "directory = '/content/ViralCutter/tmp'\n",
477 | "zip_filename = '/content/ViralCutter/videos_original_scale.zip'\n",
478 | "\n",
479 | "# Criar um arquivo zip\n",
480 | "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
481 | " # Iterar sobre os arquivos no diretório\n",
482 | " for root, dirs, files in os.walk(directory):\n",
483 | " for file in files:\n",
484 | " if file.endswith('_original_scale.mp4'):\n",
485 | " # Adicionar o arquivo ao zip\n",
486 | " zipf.write(os.path.join(root, file), arcname=file)\n",
487 | "\n",
488 | "# Fazer o download do arquivo zip\n",
489 | "from google.colab import files\n",
490 | "files.download(zip_filename)\n"
491 | ],
492 | "metadata": {
493 | "cellView": "form",
494 | "id": "X0b_jKmX2y27"
495 | },
496 | "execution_count": null,
497 | "outputs": []
498 | },
499 | {
500 | "cell_type": "code",
501 | "source": [
502 | "#@title Baixar todos os virais gerados (com legendas queimadas)\n",
503 | "\n",
504 | "!zip -r /content/burned_sub.zip /content/ViralCutter/burned_sub\n",
505 | "from google.colab import files\n",
506 | "files.download(\"/content/burned_sub.zip\")\n"
507 | ],
508 | "metadata": {
509 | "id": "22ebNo4GHVYU",
510 | "cellView": "form"
511 | },
512 | "execution_count": null,
513 | "outputs": []
514 | },
515 | {
516 | "cell_type": "markdown",
517 | "source": [
518 | "# ⚠️⚠️⚠️LIMPAR TUDO E COMEÇAR DE NOVO⚠️⚠️⚠️"
519 | ],
520 | "metadata": {
521 | "id": "qalspjsjh3ek"
522 | }
523 | },
524 | {
525 | "cell_type": "code",
526 | "source": [
527 | "#@title Apagar vídeo queimado pra gerar um novo\n",
528 | "# prompt: apagar pasta /content/burned_sub\n",
529 | "\n",
530 | "!rm -rf /content/ViralCutter/burned_sub\n"
531 | ],
532 | "metadata": {
533 | "id": "2J5qRrlEnRfc",
534 | "cellView": "form"
535 | },
536 | "execution_count": null,
537 | "outputs": []
538 | },
539 | {
540 | "cell_type": "code",
541 | "execution_count": null,
542 | "metadata": {
543 | "cellView": "form",
544 | "id": "bYjfKo3BZaXv"
545 | },
546 | "outputs": [],
547 | "source": [
548 | "#@title Limpar pastas\n",
549 | "#@markdown ATENÇÃO: Ao executar essa célula, tudo será apagado e você deve recomeçar na célula onde coloca o LINK do youtube\n",
550 | "# prompt: Apagar pasta /content/tmp\n",
551 | "\n",
552 | "!rm -rf /content/ViralCutter/tmp\n",
553 | "!rm -rf /content/ViralCutter/final\n",
554 | "!rm -rf /content/ViralCutter/subs_ass\n",
555 | "!rm -rf /content/ViralCutter/burned_sub\n",
556 | "!rm -rf /content/ViralCutter/subs\n",
557 | "\n"
558 | ]
559 | },
560 | {
561 | "cell_type": "markdown",
562 | "metadata": {
563 | "id": "nEIsMZLwJ5kD"
564 | },
565 | "source": [
566 | "#Créditos\n",
567 | "\n",
568 | "Inspirado no [reels clips automator](https://github.com/eddieoz/reels-clips-automator) e no [YoutubeVideoToAIPoweredShorts](https://github.com/Fitsbit/YoutubeVideoToAIPoweredShorts) \n",
569 | "\n",
570 | "---\n",
571 | "\n",
572 | "\n",
573 | "Desenvolvido por **Rafa.Godoy** \n",
574 | "[  ](https://github.com/rafaelGodoyEbert) \n",
575 | "[  ](https://twitter.com/GodoyEbert) \n",
576 | "[Instagram](https://www.instagram.com/rafael.godoy.ebert/) \n",
577 | "[  ](https://discord.gg/aihubbrasil)"
578 | ]
579 | },
580 | {
581 | "cell_type": "markdown",
582 | "source": [
583 | "`0.5v Alpha` \n",
584 | "\n",
585 | "Apenas uma alternativa gratuita ao `opus.pro` e ao `vidyo.ai` \n"
586 | ],
587 | "metadata": {
588 | "id": "tpLJmPqGT5_u"
589 | }
590 | }
591 | ],
592 | "metadata": {
593 | "accelerator": "GPU",
594 | "colab": {
595 | "gpuType": "T4",
596 | "provenance": []
597 | },
598 | "kernelspec": {
599 | "display_name": "Python 3",
600 | "name": "python3"
601 | },
602 | "language_info": {
603 | "name": "python"
604 | }
605 | },
606 | "nbformat": 4,
607 | "nbformat_minor": 0
608 | }
--------------------------------------------------------------------------------
/ViralCutter.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "source": [
6 | "# ViralCutter\n",
7 | "Uma alternativa gratuita ao `opus.pro` e ao `vidyo.ai`\n",
8 | "\n",
9 | "## ⚠️Você está na versão COMPLETA , se achou muito complexo, entre na versão simplificada no link abaixo.\n",
10 | "https://colab.research.google.com/drive/1aDNLtoJZa9Z0lKcYTR6CGNMgZ_iTpwJD?usp=sharing"
11 | ],
12 | "metadata": {
13 | "id": "pa36OeArowme"
14 | }
15 | },
16 | {
17 | "cell_type": "markdown",
18 | "source": [
19 | "# Suporte em:\n",
20 | "[  ](https://discord.gg/aihubbrasil)"
21 | ],
22 | "metadata": {
23 | "id": "6Q-ljfsw1unE"
24 | }
25 | },
26 | {
27 | "cell_type": "code",
28 | "source": [
29 | "#@title Áudio Mudo\n",
30 | "%%html\n",
31 | ""
32 | ],
33 | "metadata": {
34 | "cellView": "form",
35 | "colab": {
36 | "base_uri": "https://localhost:8080/",
37 | "height": 93
38 | },
39 | "id": "-ry4FVGroylp",
40 | "outputId": "9084b31f-9b46-404a-e908-f92d28a744f7"
41 | },
42 | "execution_count": null,
43 | "outputs": [
44 | {
45 | "output_type": "display_data",
46 | "data": {
47 | "text/plain": [
48 | ""
49 | ],
50 | "text/html": [
51 | "\n"
52 | ]
53 | },
54 | "metadata": {}
55 | }
56 | ]
57 | },
58 | {
59 | "cell_type": "markdown",
60 | "source": [
61 | "# TODO📝\n",
62 | "- [x] Release code\n",
63 | "- [ ] Huggingface SpaceDemo\n",
64 | "- [x] Two face in the cut\n",
65 | "- [x] Custom caption and burn\n",
66 | "- [ ] Make the code faster\n",
67 | "- [ ] More types of framing beyond 9:16"
68 | ],
69 | "metadata": {
70 | "id": "0o3KcBT5wzws"
71 | }
72 | },
73 | {
74 | "cell_type": "code",
75 | "execution_count": null,
76 | "metadata": {
77 | "cellView": "form",
78 | "id": "e76jiRnjONmj",
79 | "colab": {
80 | "base_uri": "https://localhost:8080/"
81 | },
82 | "outputId": "122bb7b6-efcc-497c-e74b-853c7f7329e1"
83 | },
84 | "outputs": [
85 | {
86 | "output_type": "stream",
87 | "name": "stdout",
88 | "text": [
89 | "Finalizado...\n"
90 | ]
91 | }
92 | ],
93 | "source": [
94 | "#@title Dependência\n",
95 | "from IPython.display import clear_output\n",
96 | "!git clone https://github.com/RafaelGodoyEbert/ViralCutter.git\n",
97 | "!pip install -U g4f[all] -q\n",
98 | "!pip install yt_dlp -q\n",
99 | "!pip install ffmpeg-python -q\n",
100 | "!pip install git+https://github.com/m-bain/whisperx.git -q\n",
101 | "!pip install mediapipe -q\n",
102 | "%cd /content/ViralCutter\n",
103 | "clear_output()\n",
104 | "print(\"Finalizado...\")"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "source": [
110 | "#@title Configuração\n",
111 | "import os\n",
112 | "from scripts import download_video, transcribe_video, create_viral_segments, cut_segments, edit_video, transcribe_cuts, adjust_subtitles, burn_subtitles, save_json\n",
113 | "from IPython.display import clear_output\n",
114 | "\n",
115 | "# Create necessary directories\n",
116 | "os.makedirs('tmp', exist_ok=True)\n",
117 | "os.makedirs('final', exist_ok=True)\n",
118 | "os.makedirs('subs', exist_ok=True)\n",
119 | "os.makedirs('subs_ass', exist_ok=True)\n",
120 | "os.makedirs('burned_sub', exist_ok=True)\n",
121 | "\n",
122 | "# Cores originais invertidas\n",
123 | "vermelho = \"0A08E4\"\n",
124 | "amarelo = \"00FFFF\"\n",
125 | "azul = \"700206\"\n",
126 | "preto = \"000000\"\n",
127 | "verde = \"58DA7D\"\n",
128 | "branco = \"FFFFFF\"\n",
129 | "laranja = \"0099FE\"\n",
130 | "roxo = \"800080\"\n",
131 | "rosa = \"C77DF9\"\n",
132 | "ciano = \"FFFF00\"\n",
133 | "marrom = \"2D4A8C\"\n",
134 | "cinza = \"808080\"\n",
135 | "verde_limao = \"32CD32\"\n",
136 | "azul_claro = \"E6D8AD\"\n",
137 | "verde = \"0FF00\"\n",
138 | "\n",
139 | "#@markdown Se quiser pular apenas para a parte de refazer a edição as legendas, ative-o\n",
140 | "# Burn subtitles option\n",
141 | "burn_only = False #@param{type:\"boolean\"}\n",
142 | "\n",
143 | "#@markdown ---\n",
144 | "#@markdown 🎬 Configurações do Vídeo 🎬 \n",
145 | "\n",
146 | "#@markdown ---\n",
147 | "#@markdown 🔗 Link do vídeo no YouTube \n",
148 | "url = 'https://youtu.be/1ZnwqFh3CrA?si=zpSig52k11NY7que' # @param {type: \"string\"}\n",
149 | "#@markdown ---\n",
150 | "#@markdown 📊 Quantidade de segmentos \n",
151 | "num_segments = 3 # @param {type:\"number\"}\n",
152 | "#@markdown ---\n",
153 | "#@markdown 🌟 Modo viral \n",
154 | "viral_mode = True #@param{type:\"boolean\"}\n",
155 | "#@markdown ---\n",
156 | "#@markdown 🔤 Legendas queimadas \n",
157 | "burn_subtitles_option = True # @param [\"False\", \"True\"] {type:\"raw\"}\n",
158 | "#@markdown ---\n",
159 | "#@markdown 🎨 Tema personalizado (caso não use modo viral) \n",
160 | "themes = '' # @param {type:\"string\", placeholder:\"Se `viral_mode` desmarcado, coloque o tema aqui, se mais que um, separado por virgulas\"}\n",
161 | "#@markdown ---\n",
162 | "#@markdown 🧠 Modelo para análise de vídeo \n",
163 | "model = 'large-v3' # @param ['base', 'large-v3']\n",
164 | "\n",
165 | "#@markdown ---\n",
166 | "#@markdown ⏳ Configurações de Tempo ⏳ \n",
167 | "\n",
168 | "#@markdown ---\n",
169 | "#@markdown ⌛ Tempo mínimo (segundos) \n",
170 | "tempo_minimo = 15 #@param{type: \"number\"}\n",
171 | "#@markdown ---\n",
172 | "#@markdown ⏳ Tempo máximo (segundos) \n",
173 | "tempo_maximo = 90 #@param{type: \"number\"}\n",
174 | "\n",
175 | "#@markdown ---\n",
176 | "#@markdown 💬 Configurações de Legendas 💬 \n",
177 | "#@markdown ⚠️ Só mexa se ``burn_subtitles_option`` estiver ativo! \n",
178 | "\n",
179 | "#@markdown ---\n",
180 | "#@markdown ### Fonte da legenda\n",
181 | "fonte = \"Arial\" #@param{type: \"string\"}\n",
182 | "#@markdown ---\n",
183 | "#@markdown ### Tamanho da fonte\n",
184 | "base_size = 12 #@param{type: \"number\"}\n",
185 | "#@markdown ---\n",
186 | "#@markdown ### Cor da fonte\n",
187 | "base_color_c = \"FFFFFF\" #@param{type: \"string\"}\n",
188 | "#@markdown ---\n",
189 | "#@markdown ### Transparência da fonte (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
190 | "base_color_t = \"00\" #@param{type: \"string\"}\n",
191 | "base_color = f\"&H{base_color_t}\" + base_color_c + \"&\"\n",
192 | "\n",
193 | "#@markdown ---\n",
194 | "#@markdown ### Cor do contorno\n",
195 | "contorno_c = \"808080\" #@param{type: \"string\"}\n",
196 | "#@markdown ---\n",
197 | "#@markdown ### Transparência da fonte (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
198 | "contorno_t = \"00\" #@param{type: \"string\"}\n",
199 | "contorno = f\"&H{contorno_t}\" + contorno_c + \"&\"\n",
200 | "\n",
201 | "#@markdown ---\n",
202 | "#@markdown ### Tamanho do highlight\n",
203 | "h_size = 14 #@param{type: \"number\"}\n",
204 | "\n",
205 | "#@markdown ---\n",
206 | "#@markdown ### Número de palavras por bloco\n",
207 | "palavras_por_bloco = 5 #@param{type: \"number\"}\n",
208 | "\n",
209 | "#@markdown ---\n",
210 | "#@markdown ### Limite de gap entre falas (em segundos)\n",
211 | "limite_gap = 0.5 #@param{type: \"number\"}\n",
212 | "\n",
213 | "#@markdown ---\n",
214 | "#@markdown ### Modo de exibição das legendas\n",
215 | "modo = 'highlight' # @param ['highlight', 'sem_higlight', 'palavra_por_palavra']\n",
216 | "\n",
217 | "#@markdown ---\n",
218 | "#@markdown 🎨 Configurações do Destaque \n",
219 | "\n",
220 | "#@markdown ---\n",
221 | "#@markdown ### Cor da fonte de destaque\n",
222 | "highlight_color_c = \"0FF00\" #@param{type: \"string\"}\n",
223 | "#@markdown ---\n",
224 | "#@markdown ### Transparência da fonte de destaque (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
225 | "highlight_color_t = \"00\" #@param{type: \"string\"}\n",
226 | "highlight_color = f\"&H{highlight_color_t}\" + highlight_color_c + \"&\"\n",
227 | "\n",
228 | "#@markdown ---\n",
229 | "#@markdown ### Posição vertical da legenda (1=170, 2=130, 3=99, 4=60 (default), 5=20)\n",
230 | "posicao_vertical = 60 #@param{type: \"number\"}\n",
231 | "\n",
232 | "#@markdown ---\n",
233 | "#@markdown ### Cor da sombra\n",
234 | "cor_da_sombra_c = \"000000\" #@param{type: \"string\"}\n",
235 | "#@markdown ---\n",
236 | "#@markdown ### Transparência da fonte (00= opaco, 80= 50% transparente, FF= totalmente transparente)\n",
237 | "cor_da_sombra_t = \"00\" #@param{type: \"string\"}\n",
238 | "cor_da_sombra = f\"&H{cor_da_sombra_t}\" + cor_da_sombra_c + \"&\"\n",
239 | "\n",
240 | "#@markdown ---\n",
241 | "#@markdown ### Alinhamento do texto\n",
242 | "#@markdown 1 = Esquerda, 2 = Centro (default), 3 = Direita\n",
243 | "alinhamento = 2 #@param{type: \"slider\", min: 1, max: 3}\n",
244 | "\n",
245 | "#@markdown ---\n",
246 | "#@markdown ### Efeitos no texto\n",
247 | "negrito = 0 #@param{type: \"number\"}\n",
248 | "italico = 0 #@param{type: \"number\"}\n",
249 | "sublinhado = 0 #@param{type: \"number\"}\n",
250 | "tachado = 0 #@param{type: \"number\"}\n",
251 | "\n",
252 | "#@markdown ---\n",
253 | "#@markdown ### Estilo da borda\n",
254 | "#@markdown 1 = Contorno, 3 = Caixa\n",
255 | "estilo_da_borda = 3 #@param{type: \"number\"}\n",
256 | "\n",
257 | "#@markdown ---\n",
258 | "#@markdown ### Espessura do contorno\n",
259 | "espessura_do_contorno = 1.5 #@param{type: \"number\"}\n",
260 | "\n",
261 | "#@markdown ---\n",
262 | "#@markdown ### Tamanho da sombra\n",
263 | "tamanho_da_sombra = 10 #@param{type: \"number\"}\n",
264 | "\n",
265 | "if burn_only:\n",
266 | " print(\"Burn only mode activated. Skipping to subtitle burning...\")\n",
267 | " burn_subtitles.burn()\n",
268 | " print(\"Subtitle burning completed.\")\n",
269 | "else:\n",
270 | " # Execute the pipeline\n",
271 | " input_video = download_video.download(url)\n",
272 | " srt_file, tsv_file = transcribe_video.transcribe(input_video, model)\n",
273 | " clear_output()\n",
274 | " viral_segments = create_viral_segments.create(num_segments, viral_mode, themes, tempo_minimo, tempo_maximo)\n",
275 | " save_json.save_viral_segments(viral_segments)\n",
276 | "\n",
277 | " cut_segments.cut(viral_segments)\n",
278 | " edit_video.edit()\n",
279 | "\n",
280 | " if burn_subtitles_option:\n",
281 | " import subprocess\n",
282 | " def transcribe():\n",
283 | " def generate_whisperx(input_file, output_folder, model=model):\n",
284 | " output_file = os.path.join(output_folder, f\"{os.path.splitext(os.path.basename(input_file))[0]}.srt\")\n",
285 | " json_file = os.path.join(output_folder, f\"{os.path.splitext(os.path.basename(input_file))[0]}.json\") # Define the JSON output file\n",
286 | "\n",
287 | " # Skip processing if the JSON file already exists\n",
288 | " if os.path.exists(json_file):\n",
289 | " print(f\"Arquivo já existe, pulando: {json_file}\")\n",
290 | " return\n",
291 | "\n",
292 | " command = f\"\"\"\n",
293 | " whisperx {input_file} \\\n",
294 | " --model {model} \\\n",
295 | " --task transcribe \\\n",
296 | " --align_model WAV2VEC2_ASR_LARGE_LV60K_960H \\\n",
297 | " --chunk_size 10 \\\n",
298 | " --vad_onset 0.4 \\\n",
299 | " --vad_offset 0.3 \\\n",
300 | " --compute_type float32 \\\n",
301 | " --batch_size 10 \\\n",
302 | " --output_dir {output_folder} \\\n",
303 | " --output_format srt \\\n",
304 | " --output_format json \\\n",
305 | " \"\"\"\n",
306 | "\n",
307 | " print(f\"Transcrevendo: {input_file}...\")\n",
308 | " result = subprocess.run(command, shell=True, text=True, capture_output=True)\n",
309 | " print(f\"Comando executado: {command}\")\n",
310 | "\n",
311 | " if result.returncode != 0:\n",
312 | " print(\"Erro durante a transcrição:\")\n",
313 | " print(result.stderr)\n",
314 | " else:\n",
315 | " print(f\"Transcrição concluída. Arquivo salvo em: {output_file} e {json_file}\")\n",
316 | " print(result.stdout) # Verificar a saída correta\n",
317 | "\n",
318 | " # Define o diretório de entrada e o diretório de saída\n",
319 | " input_folder = '/content/ViralCutter/final'\n",
320 | " output_folder = '/content/ViralCutter/subs'\n",
321 | "\n",
322 | " # Itera sobre todos os arquivos na pasta de entrada\n",
323 | " for filename in os.listdir(input_folder):\n",
324 | " if filename.endswith('.mp4'): # Filtra apenas arquivos .mp4\n",
325 | " input_file = os.path.join(input_folder, filename)\n",
326 | " generate_whisperx(input_file, output_folder)\n",
327 | "\n",
328 | " transcribe()\n",
329 | " adjust_subtitles.adjust(base_color, base_size, h_size, highlight_color, palavras_por_bloco, limite_gap, modo, posicao_vertical, alinhamento, fonte, contorno, cor_da_sombra, negrito, italico, sublinhado, tachado, estilo_da_borda, espessura_do_contorno, tamanho_da_sombra)\n",
330 | " burn_subtitles.burn() # Queimar legendas\n",
331 | " else:\n",
332 | " print(\"Subtitle burning skipped.\")\n",
333 | "\n",
334 | " print(\"Process completed successfully!\")"
335 | ],
336 | "metadata": {
337 | "cellView": "form",
338 | "id": "DNn8ZKJdD5XG",
339 | "outputId": "febdb7fc-e3c2-4d28-f523-6a347da92b16",
340 | "colab": {
341 | "base_uri": "https://localhost:8080/"
342 | }
343 | },
344 | "execution_count": null,
345 | "outputs": [
346 | {
347 | "output_type": "stream",
348 | "name": "stdout",
349 | "text": [
350 | "Diretório atual: /content/ViralCutter\n",
351 | "Transcrevendo: /content/ViralCutter/final/final-output001_processed.mp4...\n",
352 | "Comando executado: \n",
353 | " whisperx /content/ViralCutter/final/final-output001_processed.mp4 --model large-v3 --task transcribe --align_model WAV2VEC2_ASR_LARGE_LV60K_960H --chunk_size 10 --vad_onset 0.4 --vad_offset 0.3 --compute_type float32 --batch_size 10 --output_dir /content/ViralCutter/subs --output_format srt --output_format json \n",
354 | "Transcrição concluída. Arquivo salvo em: /content/ViralCutter/subs/final-output001_processed.srt e /content/ViralCutter/subs/final-output001_processed.json\n",
355 | "No language specified, language will be first be detected for each audio file (increases inference time).\n",
356 | "Model was trained with pyannote.audio 0.0.1, yours is 3.1.1. Bad things might happen unless you revert pyannote.audio to 0.x.\n",
357 | "Model was trained with torch 1.10.0+cu102, yours is 2.4.1+cu121. Bad things might happen unless you revert torch to 1.x.\n",
358 | ">>Performing transcription...\n",
359 | "Detected language: pt (1.00) in first 30s of audio...\n",
360 | "New language found (pt)! Previous was (en), loading new alignment model for new language...\n",
361 | ">>Performing alignment...\n",
362 | "\n",
363 | "Transcrevendo: /content/ViralCutter/final/final-output002_processed.mp4...\n",
364 | "Comando executado: \n",
365 | " whisperx /content/ViralCutter/final/final-output002_processed.mp4 --model large-v3 --task transcribe --align_model WAV2VEC2_ASR_LARGE_LV60K_960H --chunk_size 10 --vad_onset 0.4 --vad_offset 0.3 --compute_type float32 --batch_size 10 --output_dir /content/ViralCutter/subs --output_format srt --output_format json \n",
366 | "Transcrição concluída. Arquivo salvo em: /content/ViralCutter/subs/final-output002_processed.srt e /content/ViralCutter/subs/final-output002_processed.json\n",
367 | "No language specified, language will be first be detected for each audio file (increases inference time).\n",
368 | "Model was trained with pyannote.audio 0.0.1, yours is 3.1.1. Bad things might happen unless you revert pyannote.audio to 0.x.\n",
369 | "Model was trained with torch 1.10.0+cu102, yours is 2.4.1+cu121. Bad things might happen unless you revert torch to 1.x.\n",
370 | ">>Performing transcription...\n",
371 | "Detected language: pt (1.00) in first 30s of audio...\n",
372 | "New language found (pt)! Previous was (en), loading new alignment model for new language...\n",
373 | ">>Performing alignment...\n",
374 | "\n",
375 | "Transcrevendo: /content/ViralCutter/final/final-output000_processed.mp4...\n",
376 | "Comando executado: \n",
377 | " whisperx /content/ViralCutter/final/final-output000_processed.mp4 --model large-v3 --task transcribe --align_model WAV2VEC2_ASR_LARGE_LV60K_960H --chunk_size 10 --vad_onset 0.4 --vad_offset 0.3 --compute_type float32 --batch_size 10 --output_dir /content/ViralCutter/subs --output_format srt --output_format json \n",
378 | "Transcrição concluída. Arquivo salvo em: /content/ViralCutter/subs/final-output000_processed.srt e /content/ViralCutter/subs/final-output000_processed.json\n",
379 | "No language specified, language will be first be detected for each audio file (increases inference time).\n",
380 | "Model was trained with pyannote.audio 0.0.1, yours is 3.1.1. Bad things might happen unless you revert pyannote.audio to 0.x.\n",
381 | "Model was trained with torch 1.10.0+cu102, yours is 2.4.1+cu121. Bad things might happen unless you revert torch to 1.x.\n",
382 | ">>Performing transcription...\n",
383 | "Detected language: pt (1.00) in first 30s of audio...\n",
384 | "New language found (pt)! Previous was (en), loading new alignment model for new language...\n",
385 | ">>Performing alignment...\n",
386 | "\n",
387 | "Arquivo processado: final-output001_processed.json -> final-output001_processed.ass\n",
388 | "Arquivo processado: final-output000_processed.json -> final-output000_processed.ass\n",
389 | "Arquivo processado: final-output002_processed.json -> final-output002_processed.ass\n",
390 | "Todos os arquivos JSON foram processados e convertidos para ASS.\n",
391 | "Caminho da legenda: subs_ass/final-output001_processed.ass\n",
392 | "Processando vídeo: final-output001_processed.mp4\n",
393 | "Caminho da legenda: subs_ass/final-output001_processed.ass\n",
394 | "Caminho de saída: burned_sub/final-output001_processed_subtitled.mp4\n",
395 | "Comando: ffmpeg -i final/final-output001_processed.mp4 -vf subtitles='subs_ass/final-output001_processed.ass' -c:v h264_nvenc -preset p1 -b:v 5M -c:a copy burned_sub/final-output001_processed_subtitled.mp4\n",
396 | "Processado: burned_sub/final-output001_processed_subtitled.mp4\n",
397 | "Caminho da legenda: subs_ass/final-output002_processed.ass\n",
398 | "Processando vídeo: final-output002_processed.mp4\n",
399 | "Caminho da legenda: subs_ass/final-output002_processed.ass\n",
400 | "Caminho de saída: burned_sub/final-output002_processed_subtitled.mp4\n",
401 | "Comando: ffmpeg -i final/final-output002_processed.mp4 -vf subtitles='subs_ass/final-output002_processed.ass' -c:v h264_nvenc -preset p1 -b:v 5M -c:a copy burned_sub/final-output002_processed_subtitled.mp4\n",
402 | "Processado: burned_sub/final-output002_processed_subtitled.mp4\n",
403 | "Caminho da legenda: subs_ass/final-output000_processed.ass\n",
404 | "Processando vídeo: final-output000_processed.mp4\n",
405 | "Caminho da legenda: subs_ass/final-output000_processed.ass\n",
406 | "Caminho de saída: burned_sub/final-output000_processed_subtitled.mp4\n",
407 | "Comando: ffmpeg -i final/final-output000_processed.mp4 -vf subtitles='subs_ass/final-output000_processed.ass' -c:v h264_nvenc -preset p1 -b:v 5M -c:a copy burned_sub/final-output000_processed_subtitled.mp4\n",
408 | "Processado: burned_sub/final-output000_processed_subtitled.mp4\n",
409 | "Process completed successfully!\n",
410 | "Process completed successfully!\n"
411 | ]
412 | }
413 | ]
414 | },
415 | {
416 | "cell_type": "markdown",
417 | "source": [
418 | "Exemplo de resposta "
419 | ],
420 | "metadata": {
421 | "id": "WYquVNzP0FhO"
422 | }
423 | },
424 | {
425 | "cell_type": "code",
426 | "source": [
427 | "#@title Virais criado\n",
428 | "#@markdown Irá imprimir ``Segmento 0:``, cada número representa um vídeo para colocar na célula posterior.\n",
429 | "import json\n",
430 | "\n",
431 | "# Lê o conteúdo do arquivo viral_segments.txt\n",
432 | "with open('/content/ViralCutter/tmp/viral_segments.txt', 'r', encoding='utf-8') as file:\n",
433 | " data = json.load(file)\n",
434 | "\n",
435 | "# Itera sobre os segmentos e imprime as informações desejadas\n",
436 | "for index, segment in enumerate(data['segments']):\n",
437 | " title = segment['title']\n",
438 | " description = segment['description']\n",
439 | " score = segment['score']\n",
440 | " print(f\"Segmento {index}:\")\n",
441 | " print(f\" Título: {title}\")\n",
442 | " print(f\" Descrição: {description}\")\n",
443 | " print(f\" Score: {score}\")\n",
444 | " print()\n"
445 | ],
446 | "metadata": {
447 | "colab": {
448 | "base_uri": "https://localhost:8080/"
449 | },
450 | "cellView": "form",
451 | "id": "CH1S792_3l5q",
452 | "outputId": "634c2e33-31b7-451e-dbd2-587c06f7a1fb"
453 | },
454 | "execution_count": null,
455 | "outputs": [
456 | {
457 | "output_type": "stream",
458 | "name": "stdout",
459 | "text": [
460 | "Segmento 0:\n",
461 | " Título: Descomplicando a Vida: Menos é Mais\n",
462 | " Descrição: Discussão sobre a ideia de que estar ocupado não é uma medalha de honra e que ter tempo é um verdadeiro indicador de sucesso.\n",
463 | " Score: 85\n",
464 | "\n",
465 | "Segmento 1:\n",
466 | " Título: A Realidade do Tempo e das Tarefas\n",
467 | " Descrição: Reflexão sobre a importância de estar presente em cada momento e não se deixar levar pela pressão de fazer tudo ao mesmo tempo.\n",
468 | " Score: 90\n",
469 | "\n",
470 | "Segmento 2:\n",
471 | " Título: Aprendendo a Dizer Não\n",
472 | " Descrição: A importância de aprender a dizer não para priorizar o que realmente importa na vida, destacando o respeito próprio.\n",
473 | " Score: 80\n",
474 | "\n"
475 | ]
476 | }
477 | ]
478 | },
479 | {
480 | "cell_type": "markdown",
481 | "source": [
482 | "# Resultado em vídeo"
483 | ],
484 | "metadata": {
485 | "id": "QWVaFdjIGY4i"
486 | }
487 | },
488 | {
489 | "cell_type": "code",
490 | "execution_count": null,
491 | "metadata": {
492 | "id": "y3kiEMLqoHJ7",
493 | "cellView": "form"
494 | },
495 | "outputs": [],
496 | "source": [
497 | "#@title Resultado em vídeo\n",
498 | "#@markdown Escolha o número do vídeo\n",
499 | "from IPython.display import HTML\n",
500 | "from base64 import b64encode\n",
501 | "import json\n",
502 | "\n",
503 | "numero_do_video = 1 #@param {type:\"number\"}\n",
504 | "tipo_de_video = \"Legendas queimadas\" # @param [\"Legendas queimadas\", \"Video limpo\"]\n",
505 | "\n",
506 | "if tipo_de_video == \"Legendas queimadas\":\n",
507 | " pasta_video = 'burned_sub'\n",
508 | " sufix = 'processed_subtitled' #final-output000_\n",
509 | "else:\n",
510 | " pasta_video = 'final'\n",
511 | " sufix = 'processed'\n",
512 | "\n",
513 | "def show_video(video_path, video_width=400):\n",
514 | " video_file = open(video_path, \"r+b\").read()\n",
515 | " video_url = f\"data:video/mp4;base64,{b64encode(video_file).decode()}\"\n",
516 | " return HTML(f\"\"\" \"\"\")\n",
517 | "\n",
518 | "# Load segment information from the text file\n",
519 | "with open('/content/ViralCutter/tmp/viral_segments.txt', 'r') as file:\n",
520 | " segments_data = json.load(file)\n",
521 | "\n",
522 | "# Função para exibir o vídeo e as informações correspondentes ao índice\n",
523 | "def display_video_with_segment(index):\n",
524 | " try:\n",
525 | " segment = segments_data['segments'][index]\n",
526 | "\n",
527 | " # Print Title, Description, and Score of the segment\n",
528 | " print(f\"Título: {segment['title']}\")\n",
529 | " print(f\"Descrição: {segment['description']}\")\n",
530 | " print(f\"Score: {segment['score']}\")\n",
531 | " print()\n",
532 | "\n",
533 | " # Input video\n",
534 | " video_path = f'/content/ViralCutter/{pasta_video}/final-output{str(index).zfill(3)}_{sufix}.mp4'\n",
535 | " return show_video(video_path)\n",
536 | "\n",
537 | " except IndexError:\n",
538 | " print(f\"Segmento não encontrado para o índice {index}\")\n",
539 | " return None\n",
540 | "\n",
541 | "# Exibir vídeo e informações do segmento correspondente ao índice 0 (por exemplo)\n",
542 | "display_video_with_segment(numero_do_video) # Substitua o índice conforme necessário\n"
543 | ]
544 | },
545 | {
546 | "cell_type": "markdown",
547 | "source": [
548 | "## Baixar Zip"
549 | ],
550 | "metadata": {
551 | "id": "JXEYU0p6li2G"
552 | }
553 | },
554 | {
555 | "cell_type": "code",
556 | "source": [
557 | "#@title Baixar todos os virais gerados\n",
558 | "# prompt: Zipar e baixar todos os arquivos da pasta /content/final\n",
559 | "\n",
560 | "!zip -r /content/final.zip /content/ViralCutter/final\n",
561 | "from google.colab import files\n",
562 | "files.download(\"/content/final.zip\")\n"
563 | ],
564 | "metadata": {
565 | "cellView": "form",
566 | "id": "yV7r-PC7nmZD"
567 | },
568 | "execution_count": null,
569 | "outputs": []
570 | },
571 | {
572 | "cell_type": "code",
573 | "source": [
574 | "#@title Baixar somente Cortes com resolução original 💻\n",
575 | "#@markdown Logo vai baixar os vídeos que são somente os cortes, sem a edição e foco no rosto\n",
576 | "import os\n",
577 | "import zipfile\n",
578 | "\n",
579 | "# Definir o diretório onde os vídeos estão localizados\n",
580 | "directory = '/content/ViralCutter/tmp'\n",
581 | "zip_filename = '/content/ViralCutter/videos_original_scale.zip'\n",
582 | "\n",
583 | "# Criar um arquivo zip\n",
584 | "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
585 | " # Iterar sobre os arquivos no diretório\n",
586 | " for root, dirs, files in os.walk(directory):\n",
587 | " for file in files:\n",
588 | " if file.endswith('_original_scale.mp4'):\n",
589 | " # Adicionar o arquivo ao zip\n",
590 | " zipf.write(os.path.join(root, file), arcname=file)\n",
591 | "\n",
592 | "# Fazer o download do arquivo zip\n",
593 | "from google.colab import files\n",
594 | "files.download(zip_filename)\n"
595 | ],
596 | "metadata": {
597 | "cellView": "form",
598 | "id": "X0b_jKmX2y27"
599 | },
600 | "execution_count": null,
601 | "outputs": []
602 | },
603 | {
604 | "cell_type": "code",
605 | "source": [
606 | "#@title Baixar todos os virais gerados (com legendas queimadas)\n",
607 | "\n",
608 | "!zip -r /content/burned_sub.zip /content/ViralCutter/burned_sub\n",
609 | "from google.colab import files\n",
610 | "files.download(\"/content/burned_sub.zip\")\n"
611 | ],
612 | "metadata": {
613 | "id": "22ebNo4GHVYU",
614 | "cellView": "form"
615 | },
616 | "execution_count": null,
617 | "outputs": []
618 | },
619 | {
620 | "cell_type": "markdown",
621 | "source": [
622 | "# ⚠️⚠️⚠️LIMPAR TUDO E COMEÇAR DE NOVO⚠️⚠️⚠️"
623 | ],
624 | "metadata": {
625 | "id": "qalspjsjh3ek"
626 | }
627 | },
628 | {
629 | "cell_type": "code",
630 | "source": [
631 | "#@title Apagar vídeo queimado pra gerar um novo\n",
632 | "# prompt: apagar pasta /content/burned_sub\n",
633 | "\n",
634 | "!rm -rf /content/ViralCutter/burned_sub\n"
635 | ],
636 | "metadata": {
637 | "id": "2J5qRrlEnRfc",
638 | "cellView": "form"
639 | },
640 | "execution_count": null,
641 | "outputs": []
642 | },
643 | {
644 | "cell_type": "code",
645 | "execution_count": null,
646 | "metadata": {
647 | "cellView": "form",
648 | "id": "bYjfKo3BZaXv"
649 | },
650 | "outputs": [],
651 | "source": [
652 | "#@title Limpar pastas\n",
653 | "#@markdown ATENÇÃO: Ao executar essa célula, tudo será apagado e você deve recomeçar na célula onde coloca o LINK do youtube\n",
654 | "# prompt: Apagar pasta /content/tmp\n",
655 | "\n",
656 | "!rm -rf /content/ViralCutter/tmp\n",
657 | "!rm -rf /content/ViralCutter/final\n",
658 | "!rm -rf /content/ViralCutter/subs_ass\n",
659 | "!rm -rf /content/ViralCutter/burned_sub\n",
660 | "!rm -rf /content/ViralCutter/subs\n",
661 | "\n"
662 | ]
663 | },
664 | {
665 | "cell_type": "markdown",
666 | "metadata": {
667 | "id": "nEIsMZLwJ5kD"
668 | },
669 | "source": [
670 | "#Créditos\n",
671 | "\n",
672 | "Inspirado no [reels clips automator](https://github.com/eddieoz/reels-clips-automator) e no [YoutubeVideoToAIPoweredShorts](https://github.com/Fitsbit/YoutubeVideoToAIPoweredShorts) \n",
673 | "\n",
674 | "---\n",
675 | "\n",
676 | "\n",
677 | "Desenvolvido por **Rafa.Godoy** \n",
678 | "[  ](https://github.com/rafaelGodoyEbert) \n",
679 | "[  ](https://twitter.com/GodoyEbert) \n",
680 | "[Instagram](https://www.instagram.com/rafael.godoy.ebert/) \n",
681 | "[  ](https://discord.gg/aihubbrasil)"
682 | ]
683 | },
684 | {
685 | "cell_type": "markdown",
686 | "source": [
687 | "`0.5v Alpha` \n",
688 | "\n",
689 | "Apenas uma alternativa gratuita ao `opus.pro` e ao `vidyo.ai` \n"
690 | ],
691 | "metadata": {
692 | "id": "tpLJmPqGT5_u"
693 | }
694 | }
695 | ],
696 | "metadata": {
697 | "accelerator": "GPU",
698 | "colab": {
699 | "gpuType": "T4",
700 | "provenance": []
701 | },
702 | "kernelspec": {
703 | "display_name": "Python 3",
704 | "name": "python3"
705 | },
706 | "language_info": {
707 | "name": "python"
708 | }
709 | },
710 | "nbformat": 4,
711 | "nbformat_minor": 0
712 | }
--------------------------------------------------------------------------------
/i18n/i18n.py:
--------------------------------------------------------------------------------
1 | import json
2 | import locale
3 | import os
4 |
5 |
6 | def load_language_list(language):
7 | with open(f"./i18n/locale/{language}.json", "r", encoding="utf-8") as f:
8 | language_list = json.load(f)
9 | return language_list
10 |
11 |
12 | class I18nAuto:
13 | def __init__(self, language=None):
14 | if language in ["Auto", None]:
15 | language = locale.getdefaultlocale()[
16 | 0
17 | ] # getlocale can't identify the system's language ((None, None))
18 | if not os.path.exists(f"./i18n/locale/{language}.json"):
19 | language = "en_US"
20 | self.language = language
21 | self.language_map = load_language_list(language)
22 |
23 | def __call__(self, key):
24 | return self.language_map.get(key, key)
25 |
26 | def __repr__(self):
27 | return "Use Language: " + self.language
28 |
--------------------------------------------------------------------------------
/i18n/locale/en_US.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": "main",
3 | "Burn only mode activated. Skipping to subtitle burning...": "Burn only mode activated. Skipping to subtitle burning...",
4 | "Subtitle burning completed.": "Subtitle burning completed.",
5 | "Enter the YouTube video URL: ": "Enter the YouTube video URL: ",
6 | "Enter the number of viral segments to create: ": "Enter the number of viral segments to create: ",
7 | "\nError: Number of segments must be numeric and greater than 0.": "\nError: Number of segments must be numeric and greater than 0.",
8 | "Error: The value you entered is not an integer. Please try again.": "Error: The value you entered is not an integer. Please try again.",
9 | "Do you want viral mode? (yes/no): ": "Do you want viral mode? (yes/no): ",
10 | "Enter themes (comma-separated, leave blank if viral mode is True): ": "Enter themes (comma-separated, leave blank if viral mode is True): ",
11 | "Subtitle burning skipped.": "Subtitle burning skipped.",
12 | "Process completed successfully!": "Process completed successfully!"
13 | }
14 |
--------------------------------------------------------------------------------
/i18n/locale/pt_BR.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": "main",
3 | "Burn only mode activated. Skipping to subtitle burning...": "Modo de queima apenas ativado. Pulando para a queima de legendas...",
4 | "Subtitle burning completed.": "Queima de legendas concluída.",
5 | "Enter the YouTube video URL: ": "Insira a URL do vídeo do YouTube: ",
6 | "Enter the number of viral segments to create: ": "Insira o número de segmentos virais a serem criados: ",
7 | "\nError: Number of segments must be numeric and greater than 0.": "\nErro: O número de segmentos deve ser numérico e maior que 0.",
8 | "Error: The value you entered is not an integer. Please try again.": "Erro: O valor que você inseriu não é um número inteiro. Por favor, tente novamente.",
9 | "Do you want viral mode? (yes/no): ": "Você quer o modo viral? (yes/no): ",
10 | "Enter themes (comma-separated, leave blank if viral mode is True): ": "Insira os temas (separados por vírgula, deixe em branco se o modo viral for verdadeiro): ",
11 | "Subtitle burning skipped.": "Queima de legendas pulada.",
12 | "Process completed successfully!": "Processo concluído com sucesso!"
13 | }
14 |
--------------------------------------------------------------------------------
/i18n/locale_diff.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | from collections import OrderedDict
4 |
5 | # Define the standard file name
6 | standard_file = "locale/zh_CN.json"
7 |
8 | # Find all JSON files in the directory
9 | dir_path = "locale/"
10 | languages = [
11 | os.path.join(dir_path, f)
12 | for f in os.listdir(dir_path)
13 | if f.endswith(".json") and f != standard_file
14 | ]
15 |
16 | # Load the standard file
17 | with open(standard_file, "r", encoding="utf-8") as f:
18 | standard_data = json.load(f, object_pairs_hook=OrderedDict)
19 |
20 | # Loop through each language file
21 | for lang_file in languages:
22 | # Load the language file
23 | with open(lang_file, "r", encoding="utf-8") as f:
24 | lang_data = json.load(f, object_pairs_hook=OrderedDict)
25 |
26 | # Find the difference between the language file and the standard file
27 | diff = set(standard_data.keys()) - set(lang_data.keys())
28 |
29 | miss = set(lang_data.keys()) - set(standard_data.keys())
30 |
31 | # Add any missing keys to the language file
32 | for key in diff:
33 | lang_data[key] = key
34 |
35 | # Del any extra keys to the language file
36 | for key in miss:
37 | del lang_data[key]
38 |
39 | # Sort the keys of the language file to match the order of the standard file
40 | lang_data = OrderedDict(
41 | sorted(lang_data.items(), key=lambda x: list(standard_data.keys()).index(x[0]))
42 | )
43 |
44 | # Save the updated language file
45 | with open(lang_file, "w", encoding="utf-8") as f:
46 | json.dump(lang_data, f, ensure_ascii=False, indent=4, sort_keys=True)
47 | f.write("\n")
48 |
--------------------------------------------------------------------------------
/i18n/scan_i18n.py:
--------------------------------------------------------------------------------
1 | import ast
2 | import glob
3 | import json
4 | from collections import OrderedDict
5 |
6 |
7 | def extract_i18n_strings(node):
8 | i18n_strings = []
9 |
10 | if (
11 | isinstance(node, ast.Call)
12 | and isinstance(node.func, ast.Name)
13 | and node.func.id == "i18n"
14 | ):
15 | for arg in node.args:
16 | if isinstance(arg, ast.Str):
17 | i18n_strings.append(arg.s)
18 |
19 | for child_node in ast.iter_child_nodes(node):
20 | i18n_strings.extend(extract_i18n_strings(child_node))
21 |
22 | return i18n_strings
23 |
24 |
25 | # scan the directory for all .py files (recursively)
26 | # for each file, parse the code into an AST
27 | # for each AST, extract the i18n strings
28 |
29 | strings = []
30 | for filename in glob.iglob("**/*.py", recursive=True):
31 | with open(filename, "r") as f:
32 | code = f.read()
33 | if "I18nAuto" in code:
34 | tree = ast.parse(code)
35 | i18n_strings = extract_i18n_strings(tree)
36 | print(filename, len(i18n_strings))
37 | strings.extend(i18n_strings)
38 | code_keys = set(strings)
39 | """
40 | n_i18n.py
41 | gui_v1.py 26
42 | app.py 16
43 | infer-web.py 147
44 | scan_i18n.py 0
45 | i18n.py 0
46 | lib/train/process_ckpt.py 1
47 | """
48 | print()
49 | print("Total unique:", len(code_keys))
50 |
51 |
52 | standard_file = "i18n/locale/zh_CN.json"
53 | with open(standard_file, "r", encoding="utf-8") as f:
54 | standard_data = json.load(f, object_pairs_hook=OrderedDict)
55 | standard_keys = set(standard_data.keys())
56 |
57 | # Define the standard file name
58 | unused_keys = standard_keys - code_keys
59 | print("Unused keys:", len(unused_keys))
60 | for unused_key in unused_keys:
61 | print("\t", unused_key)
62 |
63 | missing_keys = code_keys - standard_keys
64 | print("Missing keys:", len(missing_keys))
65 | for missing_key in missing_keys:
66 | print("\t", missing_key)
67 |
68 | code_keys_dict = OrderedDict()
69 | for s in strings:
70 | code_keys_dict[s] = s
71 |
72 | # write back
73 | with open(standard_file, "w", encoding="utf-8") as f:
74 | json.dump(code_keys_dict, f, ensure_ascii=False, indent=4, sort_keys=True)
75 | f.write("\n")
76 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | from scripts import download_video, transcribe_video, create_viral_segments, cut_segments, edit_video, transcribe_cuts, adjust_subtitles, burn_subtitles, save_json
3 | from i18n.i18n import I18nAuto
4 | i18n = I18nAuto()
5 |
6 | # Create necessary directories
7 | os.makedirs('tmp', exist_ok=True)
8 | os.makedirs('final', exist_ok=True)
9 | os.makedirs('subs', exist_ok=True)
10 | os.makedirs('subs_ass', exist_ok=True)
11 | os.makedirs('burned_sub', exist_ok=True)
12 |
13 | # Cores originais invertidas
14 | vermelho = "0A08E4"
15 | amarelo = "00FFFF"
16 | azul = "700206"
17 | preto = "000000"
18 | verde = "58DA7D"
19 | branco = "FFFFFF"
20 | laranja = "0099FE"
21 | roxo = "800080"
22 | rosa = "C77DF9"
23 | ciano = "FFFF00"
24 | marrom = "2D4A8C"
25 | cinza = "808080"
26 | verde_limao = "32CD32"
27 | azul_claro = "E6D8AD"
28 | verde = "0FF00"
29 |
30 | # Subtitle variables
31 | fonte = "Arial" #Arial, Times New Roman #No colab acho que todas do Google Fonts, no Windows/Linux as instaladas no seu sistema
32 | base_size = 12 #12
33 | base_color_t = "00" # 00= totalmente opaco, 80= 50% transparente, FF= Totalmente transparente
34 | base_color = f"&H{base_color_t}" + "FFFFFF" + "&" #FFFFFF (branco) ou 00FFFF (amarelo)
35 | contorno_t = "FF" # 00= totalmente opaco, 80= 50% transparente, FF= Totalmente transparente
36 | contorno = f"&H{contorno_t}" + "808080" + "&" #808080
37 | h_size = 14 #14 (Default)
38 | palavras_por_bloco = 3 #5 (Default)
39 | limite_gap = 0.5 #0.5 (Default)
40 | modo = 'highlight' #sem_higlight, palavra_por_palavra, highlight
41 | highlight_color_t = "00" # 00= totalmente opaco, 80= 50% transparente, FF= Totalmente transparente
42 | highlight_color = f"&H{highlight_color_t}" + "0FF00" + "&" #0FF00
43 | posicao_vertical = 60 # Divide de 1 à 5 contando um no topo. 1=170, 2=130, 3=99, 4=60 (default), 5=20
44 | cor_da_sombra_t = "00" # 00= totalmente opaco, 80= 50% transparente, FF= Totalmente transparente
45 | cor_da_sombra = f"&H{cor_da_sombra_t}" + "000000" + "&" #000000
46 | alinhamento = 2 #1= Esquerda, 2= Centro (default), 3= Direita
47 | negrito = 0 #(1 para ativar, 0 para desativar)
48 | italico = 0 #(1 para ativar, 0 para desativar)
49 | sublinhado = 0 #(1 para ativar, 0 para desativar)
50 | tachado = 0 #(1 para ativar, 0 para desativar)
51 | estilo_da_borda = 3 #(1 para contorno, 3 para caixa).
52 | espessura_do_contorno = 1.5 #1.5 (Default)
53 | tamanho_da_sombra = 10 #10 (Default)
54 |
55 | # Burn subtitles option
56 | burn_only = False
57 | burn_subtitles_option = True
58 |
59 | # Transcript variables
60 | model = 'large-v3'
61 |
62 | if burn_only:
63 | print(i18n("Burn only mode activated. Skipping to subtitle burning..."))
64 | burn_subtitles.burn()
65 | print(i18n("Subtitle burning completed."))
66 | else:
67 | # Input variables
68 | url = input(i18n("Enter the YouTube video URL: "))
69 |
70 | while True:
71 | try:
72 | num_segments = int(input(i18n("Enter the number of viral segments to create: ")))
73 | if num_segments < 1:
74 | print(i18n("\nError: Number of segments must be numeric and greater than 0."))
75 | else:
76 | break
77 | except ValueError:
78 | print(i18n("\nError: The value you entered is not an integer. Please try again."))
79 |
80 | viral_mode = input(i18n("Do you want viral mode? (yes/no): ")).lower() == 'yes' or 'y'
81 | themes = input(i18n("Enter themes (comma-separated, leave blank if viral mode is True): ")) if not viral_mode else ''
82 |
83 | tempo_minimo = 15 #int(input("Enter the minimum duration for segments (in seconds): "))
84 | tempo_maximo = 90 #int(input("Enter the maximum duration for segments (in seconds): "))
85 |
86 | # Execute the pipeline
87 | input_video = download_video.download(url)
88 | srt_file, tsv_file = transcribe_video.transcribe(input_video, model)
89 |
90 | viral_segments = create_viral_segments.create(num_segments, viral_mode, themes, tempo_minimo, tempo_maximo)
91 | save_json.save_viral_segments(viral_segments)
92 |
93 | cut_segments.cut(viral_segments)
94 | edit_video.edit()
95 |
96 | if burn_subtitles_option:
97 | transcribe_cuts.transcribe()
98 | adjust_subtitles.adjust(base_color, base_size, h_size, highlight_color, palavras_por_bloco, limite_gap, modo, posicao_vertical, alinhamento, fonte, contorno, cor_da_sombra, negrito, italico, sublinhado, tachado, estilo_da_borda, espessura_do_contorno, tamanho_da_sombra)
99 | burn_subtitles.burn()
100 | else:
101 | print(i18n("Subtitle burning skipped."))
102 |
103 | print(i18n("Process completed successfully!"))
--------------------------------------------------------------------------------
/scripts/adjust_subtitles.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | import os
4 |
5 | def adjust(base_color, base_size, h_size, highlight_color, palavras_por_bloco, limite_gap, modo, posicao_vertical, alinhamento, fonte, contorno, cor_da_sombra,negrito,italico, sublinhado, tachado, estilo_da_borda,espessura_do_contorno, tamanho_da_sombra):
6 | def gerar_ass(json_data, arquivo_saida, base_color=base_color, base_size=base_size, h_size=h_size, highlight_color=highlight_color, palavras_por_bloco=palavras_por_bloco, limite_gap=limite_gap, modo=modo, posicao_vertical=posicao_vertical, alinhamento=alinhamento, fonte=fonte, contorno=contorno, cor_da_sombra=cor_da_sombra, negrito=negrito, italico=italico, sublinhado=sublinhado, tachado=tachado, estilo_da_borda=estilo_da_borda, espessura_do_contorno=espessura_do_contorno, tamanho_da_sombra=tamanho_da_sombra):
7 | header_ass = f"""[Script Info]
8 | Title: Legendas Dinâmicas
9 | ScriptType: v4.00+
10 | PlayDepth: 0
11 |
12 | [V4+ Styles]
13 | Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
14 | Style: Default,{fonte},{base_size},{base_color},&H00000000,{contorno},{cor_da_sombra},{negrito},{italico},{sublinhado},{tachado},100,100,0,0,{estilo_da_borda},{espessura_do_contorno},{tamanho_da_sombra},{alinhamento},-2,-2,{posicao_vertical},1
15 |
16 | [Events]
17 | Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
18 | """
19 | # Style: Default,{fonte},{base_size},{base_color},&H00000000,{contorno},{cor_da_sombra},{negrito},{italico},{sublinhado},{tachado},100,100,0,0,1,1.5,0,{alinhamento},-2,-2,{posicao_vertical},1
20 |
21 | # 1. **Name**: `Default` - Nome do estilo.
22 | # 2. **Fontname**: `{fonte}` - Nome da fonte usada.
23 | # 3. **Fontsize**: `{base_size}` - Tamanho da fonte.
24 | # 4. **PrimaryColour**: `{base_color}` - Cor primária do texto.
25 | # 5. **SecondaryColour**: `&H00000000` - Cor secundária do texto (usada para karaokê).
26 | # 6. **OutlineColour**: `{contorno}` - Cor do contorno do texto.
27 | # 7. **BackColour**: `{cor_da_sombra}` - Cor de fundo do texto.
28 | # 8. **Bold**: `{negrito}` - Negrito (1 para ativar, 0 para desativar).
29 | # 9. **Italic**: `{italico}` - Itálico (1 para ativar, 0 para desativar).
30 | # 10. **Underline**: `{sublinhado}` - Sublinhado (1 para ativar, 0 para desativar).
31 | # 11. **StrikeOut**: `{tachado}` - Tachado (1 para ativar, 0 para desativar).
32 |
33 | # 12. **ScaleX**: `100` - Escala horizontal do texto (em porcentagem).
34 | # 13. **ScaleY**: `100` - Escala vertical do texto (em porcentagem).
35 | # 14. **Spacing**: `0` - Espaçamento entre caracteres.
36 | # 15. **Angle**: `0` - Ângulo de rotação do texto.
37 |
38 | # 16. **BorderStyle**: `{estilo_da_borda}` - Estilo da borda (1 para contorno, 3 para caixa).
39 | # 17. **Outline**: `{espessura_do_contorno}` - Espessura do contorno.
40 | # 18. **Shadow**: `{tamanho_da_sombra}` - Tamanho da sombra.
41 | # 19. **Alignment**: `{alinhamento}` - Alinhamento do texto (1 = inferior esquerdo, 2 = inferior central, 3 = inferior direito, 4 = meio esquerdo, 5 = meio central, 6 = meio direito, 7 = superior esquerdo, 8 = superior central, 9 = superior direito)
42 |
43 | # 20. **MarginL**: `-2` - Margem esquerda.
44 | # 21. **MarginR**: `-2` - Margem direita.
45 | # 22. **MarginV**: `60` - Margem vertical.
46 | # 23. **Encoding**: `1` - Codificação da fonte (0 para ANSI, 1 para Default, etc.).
47 |
48 | with open(arquivo_saida, "w", encoding="utf-8") as f:
49 | f.write(header_ass)
50 |
51 | for segment in json_data.get('segments', []):
52 | words = segment.get('words', [])
53 | total_words = len(words)
54 |
55 | i = 0
56 | while i < total_words:
57 | block = []
58 | while len(block) < palavras_por_bloco and i < total_words:
59 | current_word = words[i]
60 | if 'word' in current_word:
61 | cleaned_word = re.sub(r'[.,!?;]', '', current_word['word'])
62 | block.append({**current_word, 'word': cleaned_word})
63 |
64 | if i + 1 < total_words:
65 | next_word = words[i + 1]
66 | if 'start' not in next_word or 'end' not in next_word:
67 | next_cleaned_word = re.sub(r'[.,!?;]', '', next_word['word'])
68 | block[-1]['word'] += " " + next_cleaned_word
69 | i += 1
70 | i += 1
71 |
72 | start_times = [word.get('start', 0) for word in block]
73 | end_times = [word.get('end', 0) for word in block]
74 |
75 | if modo == "highlight":
76 | for j in range(len(block)):
77 | line = ""
78 | for k, word_data in enumerate(block):
79 | word = word_data['word']
80 | if k == j:
81 | line += f"{{\\fs{h_size}\\c{highlight_color}}}{word} "
82 | else:
83 | line += f"{{\\fs{base_size}\\c{base_color}}}{word} "
84 |
85 | start_time_ass = format_time_ass(start_times[j])
86 | if j > 0 and (start_times[j] - end_times[j - 1] < limite_gap):
87 | start_time_ass = format_time_ass(end_times[j - 1])
88 |
89 | end_time_ass = format_time_ass(end_times[j])
90 |
91 | f.write(f"Dialogue: 0,{start_time_ass},{end_time_ass},Default,,0,0,0,,{line.strip()}\n")
92 |
93 | elif modo == "sem_higlight":
94 | for j in range(len(block)):
95 | line = " ".join(word_data['word'] for word_data in block)
96 |
97 | start_time_ass = format_time_ass(start_times[j])
98 | if j > 0 and (start_times[j] - end_times[j - 1] < limite_gap):
99 | start_time_ass = format_time_ass(end_times[j - 1])
100 |
101 | end_time_ass = format_time_ass(end_times[j])
102 |
103 | f.write(f"Dialogue: 0,{start_time_ass},{end_time_ass},Default,,0,0,0,,{line.strip()}\n")
104 |
105 | elif modo == "palavra_por_palavra":
106 | for j in range(len(block)):
107 | line = block[j]['word']
108 | start_time_ass = format_time_ass(start_times[j])
109 | end_time_ass = format_time_ass(end_times[j])
110 | f.write(f"Dialogue: 0,{start_time_ass},{end_time_ass},Default,,0,0,0,,{line.strip()}\n")
111 |
112 | def format_time_ass(time_seconds):
113 | hours = int(time_seconds // 3600)
114 | minutes = int((time_seconds % 3600) // 60)
115 | seconds = int(time_seconds % 60)
116 | centiseconds = int((time_seconds % 1) * 100)
117 | return f"{hours:01}:{minutes:02}:{seconds:02}.{centiseconds:02}"
118 |
119 | # Diretórios de entrada e saída
120 | input_dir = "subs"
121 | output_dir = "subs_ass"
122 |
123 | # Criar o diretório de saída se não existir
124 | os.makedirs(output_dir, exist_ok=True)
125 |
126 | # Processar todos os arquivos JSON na pasta de entrada
127 | for filename in os.listdir(input_dir):
128 | if filename.endswith(".json"):
129 | input_path = os.path.join(input_dir, filename)
130 | output_filename = os.path.splitext(filename)[0] + ".ass"
131 | output_path = os.path.join(output_dir, output_filename)
132 |
133 | # Carregar o arquivo JSON
134 | with open(input_path, "r", encoding="utf-8") as file:
135 | json_data = json.load(file)
136 |
137 | # Gerar o arquivo ASS
138 | gerar_ass(json_data, output_path, modo=modo, palavras_por_bloco=palavras_por_bloco, posicao_vertical=posicao_vertical, alinhamento=alinhamento)
139 |
140 | print(f"Arquivo processado: {filename} -> {output_filename}")
141 |
142 | print("Todos os arquivos JSON foram processados e convertidos para ASS.")
--------------------------------------------------------------------------------
/scripts/burn_subtitles.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import sys
4 |
5 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
6 |
7 | def burn():
8 | # Caminhos das pastas
9 | subs_folder = 'subs_ass'
10 | videos_folder = 'final'
11 | output_folder = 'burned_sub' # Pasta para salvar os vídeos com legendas
12 |
13 | # Cria a pasta de saída se não existir
14 | os.makedirs(output_folder, exist_ok=True)
15 |
16 | # Itera sobre os arquivos de vídeo na pasta final
17 | for video_file in os.listdir(videos_folder):
18 | if video_file.endswith(('.mp4', '.mkv', '.avi')): # Formatos suportados
19 | # Extrai o nome base do vídeo (sem extensão)
20 | video_name = os.path.splitext(video_file)[0]
21 |
22 | # Define o caminho para a legenda correspondente
23 | subtitle_file = os.path.join(subs_folder, f"{video_name}.ass")
24 | print(f"Caminho da legenda: {subtitle_file}")
25 |
26 | # Verifica se a legenda existe
27 | if os.path.exists(subtitle_file):
28 | # Define o caminho de saída para o vídeo com legendas
29 | output_file = os.path.join(output_folder, f"{video_name}_subtitled.mp4")
30 |
31 | # Ajuste no caminho da legenda para FFmpeg
32 | subtitle_file_ffmpeg = subtitle_file.replace('\\', '/')
33 |
34 | # Comando FFmpeg para adicionar as legendas
35 | command = [
36 | 'ffmpeg',
37 | '-i', os.path.join(videos_folder, video_file), # Vídeo de entrada
38 | '-vf', f"subtitles='{subtitle_file_ffmpeg}'", # Filtro de legendas com caminho corrigido
39 | '-c:v', 'h264_nvenc', # Codificador NVIDIA
40 | '-preset', 'p1', # Preset para velocidade
41 | '-b:v', '5M', # Bitrate
42 | '-c:a', 'copy', # Copia o áudio
43 | output_file
44 | ]
45 |
46 | # Log dos caminhos e do comando
47 | print(f"Processando vídeo: {video_file}")
48 | print(f"Caminho da legenda: {subtitle_file}")
49 | print(f"Caminho de saída: {output_file}")
50 | print(f"Comando: {' '.join(command)}")
51 |
52 | # Executa o comando
53 | try:
54 | subprocess.run(command, check=True)
55 | print(f"Processado: {output_file}")
56 | except subprocess.CalledProcessError as e:
57 | print(f"Erro ao processar {video_name}: {e}")
58 | else:
59 | print(f"Legenda não encontrada para: {video_name}")
60 |
61 |
--------------------------------------------------------------------------------
/scripts/create_viral_segments.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | def create(num_segments, viral_mode, themes, tempo_minimo, tempo_maximo):
4 | quantidade_de_virals = num_segments # @param {type:"number"}
5 |
6 | with open('tmp/input_video.tsv', 'r', encoding='utf-8') as f:
7 | content = f.read()
8 |
9 | system = f"You are a Viral Segment Identifier, an AI system that analyzes a video's transcript and predicts which segments might go viral on social media platforms. You use factors such as emotional impact, humor, unexpected content, and relevance to current trends to make your predictions. You return a structured text document detailing the start and end times, the description, the duration, and a viral score for the potential viral segments."
10 |
11 | json_template = '''
12 | { "segments" :
13 | [
14 | {
15 | "title": "Suggested Viral Title",
16 | "start_time": "00:00:00", #HH:MM:SS
17 | "end_time": "00:00:00", #HH:MM:SS
18 | "description": "Description of the text",
19 | "duration": 0,
20 | "score": 0 # Probability of going viral (0-100)
21 | }
22 | ]
23 | }
24 | '''
25 |
26 | # Split content into chunks of 14,000 characters without cutting lines
27 | chunk_size = 17400
28 | chunks = []
29 | start = 0
30 |
31 | while start < len(content):
32 | end = min(start + chunk_size, len(content))
33 | if end < len(content):
34 | end = content.rfind('\n', start, end) # Find last newline before chunk size
35 | if end == -1: # No newline found, just take the chunk size
36 | end = start + chunk_size
37 | chunks.append(content[start:end])
38 | start = end
39 |
40 | # Prepare the output texts
41 | #@markdown Se viral está marcado, os temas não serão executados.
42 | viral = None #@param{type:"boolean"}
43 | #@markdown Se viral está desmarcado, a IA vai procurar os temas selecionadas
44 |
45 | #@markdown Exemplo: ``GTA VI, cadeirada datena, as luas de júpiter``
46 | temas = '' # @param {type:"string", placeholder:"Coloque o tema aqui, se mais que um, separado por virgulas"}
47 |
48 | if viral_mode:
49 | type = f"""analyze the segment for potential virality and identify {quantidade_de_virals} most viral segments from the transcript"""
50 | else:
51 | type = f"""analyze the segment for potential virality and identify {quantidade_de_virals} the best parts based on the list of themes {themes}."""
52 |
53 | output_texts = []
54 | for i, chunk in enumerate(chunks):
55 | if len(chunks) == 1:
56 | output_text = f"""
57 | {system}\n
58 | Given the following video transcript, {type}. Each segment must have a duration between {tempo_minimo} and {tempo_maximo} seconds. It is MANDATORY to respect the specified number of viral segments, the minimum duration, and the maximum duration. Additionally, the cuts MUST MAKE SENSE and cannot end abruptly without context. The provided transcript is as follows:
59 | {chunk}
60 | Based on your analysis, return a structured text document containing the timestamps (start and end), the description of the viral part, its duration, a suggested viral title, and a score indicating the probability of going viral. Please follow this format for each segment.
61 | {json_template}
62 | The total duration must be within a minimum time of {tempo_minimo} seconds and a maximum time of {tempo_maximo} seconds.
63 | """
64 | else:
65 | if i == 0:
66 | output_text = f"""
67 | {chunk}
68 | """
69 | elif i < len(chunks) - 1:
70 | output_text = f"""
71 | Vou enviar outra parte da legenda, analise e responda com OK, assim envio mais partes da legenda.
72 |
73 | {chunk}
74 | """
75 | else:
76 | output_text = f"""
77 | Vou enviar outra parte da legenda, analise e responda com OK, assim envio mais partes da legenda.
78 |
79 | {chunk}\n\n
80 | {system}\n
81 | Given the following video transcript, {type}. Each segment must have a duration between {tempo_minimo} and {tempo_maximo} seconds. It is MANDATORY to respect the specified number of viral segments, the minimum duration, and the maximum duration. Additionally, the cuts MUST MAKE SENSE and cannot end abruptly without context. The provided transcript is as follows:
82 | {chunk}
83 | Based on your analysis, return a structured text document containing the timestamps (start and end), the description of the viral part, its duration, a suggested viral title, and a score indicating the probability of going viral. Please follow this format for each segment. Leave the 'title' and 'description' in the language the subtitles are in.
84 | {json_template}
85 | The total duration must be within a minimum time of {tempo_minimo} seconds and a maximum time of {tempo_maximo} seconds.
86 | """
87 |
88 | output_texts.append(output_text)
89 |
90 | # Print the output texts
91 | for text in output_texts:
92 | print(text)
--------------------------------------------------------------------------------
/scripts/cut_segments.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import subprocess
3 | import json
4 | import os
5 |
6 | def cut(segments):
7 |
8 | def check_nvenc_support():
9 | try:
10 | result = subprocess.run(["ffmpeg", "-encoders"], capture_output=True, text=True)
11 | return "h264_nvenc" in result.stdout
12 | except subprocess.CalledProcessError:
13 | return False
14 |
15 | def generate_segments(response):
16 | if not check_nvenc_support():
17 | print("NVENC is not supported on this system. Falling back to libx264.")
18 | video_codec = "libx264"
19 | else:
20 | video_codec = "h264_nvenc"
21 |
22 | input_file = "tmp/input_video.mp4"
23 | if not os.path.exists(input_file):
24 | print(f"Input file not found: {input_file}")
25 | return
26 |
27 | segments = response.get("segments", [])
28 | for i, segment in enumerate(segments):
29 | start_time = segment.get("start_time", "00:00:00")
30 | duration = segment.get("duration", 0) # Utiliza a duração para calcular o corte
31 |
32 | output_file = f"output{str(i).zfill(3)}_original_scale.mp4"
33 |
34 | # Comando ffmpeg ajustado para usar -ss antes de -i e -t para a duração
35 | command = [
36 | "ffmpeg",
37 | "-y",
38 | "-ss", start_time, # Corte antes de decodificar
39 | "-i", input_file,
40 | "-t", str(duration), # Define a duração do segmento
41 | "-c:v", video_codec
42 | ]
43 |
44 | if video_codec == "h264_nvenc":
45 | command.extend([
46 | "-preset", "p1", # Fast encoding preset for NVENC
47 | "-b:v", "5M", # Set bitrate instead of CRF for NVENC
48 | ])
49 | else:
50 | command.extend([
51 | "-preset", "ultrafast",
52 | "-crf", "23"
53 | ])
54 |
55 | command.extend([
56 | "-c:a", "aac",
57 | "-b:a", "128k",
58 | f"tmp/{output_file}"
59 | ])
60 |
61 | print(f"Processing segment {i+1}/{len(segments)}")
62 | print(f"Start time: {start_time}, Duration: {duration} seconds")
63 | print(f"Executing command: {' '.join(command)}")
64 |
65 | # Executando o comando
66 | try:
67 | result = subprocess.run(command, check=True, capture_output=True, text=True)
68 | #print(f"Command output: {result.stdout}")
69 | #print(f"Command error output: {result.stderr}")
70 | except subprocess.CalledProcessError as e:
71 | print(f"Error executing ffmpeg: {e}")
72 | #print(f"Error output: {e.stderr}")
73 | continue
74 |
75 | if os.path.exists(f"tmp/{output_file}"):
76 | file_size = os.path.getsize(f"tmp/{output_file}")
77 | print(f"Generated segment: {output_file}, Size: {file_size} bytes")
78 | else:
79 | print(f"Failed to generate segment: {output_file}")
80 |
81 | print("\n" + "="*50 + "\n")
82 |
83 | # Reading the JSON file
84 | with open('tmp/viral_segments.txt', 'r') as file:
85 | response = json.load(file)
86 |
87 | generate_segments(response)
88 |
--------------------------------------------------------------------------------
/scripts/download_video.py:
--------------------------------------------------------------------------------
1 | import os
2 | import yt_dlp
3 |
4 | def download(url):
5 | output_path = 'tmp/input_video.mp4'
6 |
7 | ydl_opts = {
8 | 'format': 'bestvideo+bestaudio/best',
9 | 'postprocessors': [{
10 | 'key': 'FFmpegVideoConvertor',
11 | 'preferedformat':'mp4'
12 | }],
13 | 'outtmpl': output_path,
14 | 'postprocessor_args': [
15 | '-movflags', 'faststart'
16 | ],
17 | 'merge_output_format':'mp4'
18 | }
19 |
20 | while True:
21 | try:
22 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
23 | ydl.download([url])
24 | break
25 | except yt_dlp.utils.DownloadError as e:
26 | if "is not a valid URL" in str(e):
27 | print("Erro: o link inserido não é válido.")
28 | url = input("\nPor favor, insira um link válido: ")
29 | else:
30 | raise
31 |
32 | return output_path
--------------------------------------------------------------------------------
/scripts/edit_video.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | import os
4 | import subprocess
5 | import mediapipe as mp
6 | from scripts.one_face import crop_and_resize_single_face, resize_with_padding, detect_face_or_body
7 | from scripts.two_face import crop_and_resize_two_faces, detect_face_or_body_two_faces
8 |
9 | def edit():
10 | # Inicialização das soluções do MediaPipe
11 | mp_face_detection = mp.solutions.face_detection
12 | mp_face_mesh = mp.solutions.face_mesh
13 | mp_pose = mp.solutions.pose
14 |
15 | def generate_short(input_file, output_file, original_file, index, num_faces):
16 | try:
17 | cap = cv2.VideoCapture(input_file)
18 |
19 | if not cap.isOpened():
20 | print(f"Erro ao abrir o vídeo: {input_file}")
21 | return
22 |
23 | fps = cap.get(cv2.CAP_PROP_FPS)
24 | frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
25 | frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
26 | total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
27 | print(f"Dimensões do vídeo - Altura: {frame_height}, Largura: {frame_width}, FPS: {fps}, Total de Frames: {total_frames}")
28 |
29 | fourcc = cv2.VideoWriter_fourcc(*'mp4v')
30 | out = cv2.VideoWriter(output_file, fourcc, fps, (1080, 1920))
31 |
32 | detection_interval = int(5 * fps) # Verificar a cada 1 segundo
33 | last_detected_faces = None
34 | last_frame_face_positions = None
35 | frames_since_last_detection = 0
36 | max_frames_without_detection = detection_interval
37 |
38 | transition_duration = int(fps) # Duração da transição suave (1 segundo)
39 | transition_frames = []
40 |
41 | # Inicializar as soluções do MediaPipe dentro de um contexto 'with' para garantir a liberação de recursos
42 | with mp_face_detection.FaceDetection(model_selection=1, min_detection_confidence=0.5) as face_detection, \
43 | mp_face_mesh.FaceMesh(static_image_mode=False, max_num_faces=2, refine_landmarks=True, min_detection_confidence=0.5, min_tracking_confidence=0.5) as face_mesh, \
44 | mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
45 |
46 | for frame_index in range(total_frames):
47 | ret, frame = cap.read()
48 | if not ret or frame is None:
49 | break
50 |
51 | # Detectar rostos ou corpos a cada 1 segundo
52 | if frame_index % detection_interval == 0:
53 | if num_faces == 2:
54 | detections = detect_face_or_body_two_faces(frame, face_detection, face_mesh, pose)
55 | else: # num_faces == 1
56 | detections = detect_face_or_body(frame, face_detection, face_mesh, pose)
57 | if detections:
58 | detections = [detections[0]] # Garantir que temos apenas uma detecção
59 |
60 | if detections and len(detections) == num_faces:
61 | if last_frame_face_positions is not None:
62 | # Iniciar transição suave
63 | start_faces = np.array(last_frame_face_positions)
64 | end_faces = np.array(detections)
65 | transition_frames = np.linspace(start_faces, end_faces, transition_duration, dtype=int)
66 | else:
67 | transition_frames = []
68 | last_detected_faces = detections
69 | frames_since_last_detection = 0
70 | else:
71 | frames_since_last_detection += 1
72 |
73 | # Aplicar transições suaves
74 | if len(transition_frames) > 0:
75 | current_faces = transition_frames[0]
76 | transition_frames = transition_frames[1:]
77 | elif last_detected_faces is not None and frames_since_last_detection <= max_frames_without_detection:
78 | current_faces = last_detected_faces
79 | else:
80 | # Redimensionar o frame com padding se nenhum rosto for detectado
81 | result = resize_with_padding(frame)
82 | out.write(result)
83 | continue
84 |
85 | # Atualizar a última posição conhecida dos rostos
86 | last_frame_face_positions = current_faces
87 |
88 | # Aplicar o crop para dois rostos ou um rosto/corpo
89 | if num_faces == 2:
90 | result = crop_and_resize_two_faces(frame, current_faces)
91 | else:
92 | result = crop_and_resize_single_face(frame, current_faces[0])
93 | out.write(result)
94 |
95 | cap.release()
96 | out.release()
97 | cv2.destroyAllWindows()
98 |
99 | # Extrair o áudio do vídeo original
100 | audio_file = f"tmp/output-audio-{index}.aac"
101 | command = f"ffmpeg -y -i {input_file} -vn -acodec copy {audio_file}"
102 |
103 | result = subprocess.run(command, shell=True, capture_output=True, text=True)
104 | if result.returncode != 0:
105 | print(f"Erro ao extrair o áudio: {result.stderr}")
106 | return
107 |
108 | if os.path.exists(audio_file) and os.path.getsize(audio_file) > 0:
109 | final_dir = "final/"
110 | os.makedirs(final_dir, exist_ok=True)
111 | final_output = os.path.join(final_dir, f"final-output{str(index).zfill(3)}_processed.mp4")
112 | command = f"ffmpeg -y -i {output_file} -i {audio_file} -c:v h264_nvenc -preset fast -b:v 2M -c:a aac -b:a 192k -r {fps} {final_output}"
113 | subprocess.call(command, shell=True)
114 | print(f"Arquivo final gerado em: {final_output}")
115 | else:
116 | print(f"Erro ao extrair o áudio do vídeo: {input_file}")
117 |
118 | except Exception as e:
119 | print(f"Erro durante o processamento do vídeo: {str(e)}")
120 |
121 |
122 | # Processar múltiplos vídeos
123 | index = 0
124 | while True:
125 | input_file = f'tmp/output{str(index).zfill(3)}_original_scale.mp4'
126 | output_file = f"tmp/output{str(index).zfill(3)}_processed.mp4"
127 | original_file = f'tmp/output{str(index).zfill(3)}.mp4'
128 |
129 | if os.path.exists(input_file):
130 | # Definir o número de rostos esperados diretamente
131 | num_faces = 2 # ou 2, conforme sua necessidade
132 | # Verificar se o número de rostos é válido
133 | if num_faces in [1, 2]:
134 | generate_short(input_file, output_file, original_file, index, num_faces)
135 | else:
136 | print("Por favor, defina num_faces como 1 ou 2.")
137 | else:
138 | print(f"Processamento completo até {index - 1} arquivos.")
139 | break
140 |
141 | index += 1
142 |
143 | if __name__ == "__main__":
144 | edit()
--------------------------------------------------------------------------------
/scripts/one_face.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | import os
4 | import subprocess
5 | import mediapipe as mp
6 |
7 | def crop_and_resize_single_face(frame, face):
8 | frame_height, frame_width = frame.shape[:2]
9 |
10 | x, y, w, h = face
11 | face_center_x = x + w // 2
12 | face_center_y = y + h // 2
13 |
14 | # Cálculo da proporção desejada (9:16)
15 | target_aspect_ratio = 9 / 16
16 |
17 | # Cálculo da área de corte para evitar barras pretas
18 | if frame_width / frame_height > target_aspect_ratio:
19 | new_width = int(frame_height * target_aspect_ratio)
20 | new_height = frame_height
21 | else:
22 | new_width = frame_width
23 | new_height = int(frame_width / target_aspect_ratio)
24 |
25 | # Garantir que o corte esteja dentro dos limites
26 | crop_x = max(0, min(face_center_x - new_width // 2, frame_width - new_width))
27 | crop_y = max(0, min(face_center_y - new_height // 2, frame_height - new_height))
28 | crop_x2 = crop_x + new_width
29 | crop_y2 = crop_y + new_height
30 |
31 | # Recorte e redimensionamento para 1080x1920 (9:16)
32 | crop_img = frame[crop_y:crop_y2, crop_x:crop_x2]
33 | resized = cv2.resize(crop_img, (1080, 1920), interpolation=cv2.INTER_AREA)
34 |
35 | return resized
36 |
37 | def resize_with_padding(frame):
38 | frame_height, frame_width = frame.shape[:2]
39 | target_aspect_ratio = 9 / 16
40 |
41 | if frame_width / frame_height > target_aspect_ratio:
42 | new_width = frame_width
43 | new_height = int(frame_width / target_aspect_ratio)
44 | else:
45 | new_height = frame_height
46 | new_width = int(frame_height * target_aspect_ratio)
47 |
48 | # Criação de uma tela preta
49 | result = np.zeros((new_height, new_width, 3), dtype=np.uint8)
50 |
51 | # Cálculo das margens
52 | pad_top = (new_height - frame_height) // 2
53 | pad_left = (new_width - frame_width) // 2
54 |
55 | # Colocar o frame original na tela
56 | result[pad_top:pad_top+frame_height, pad_left:pad_left+frame_width] = frame
57 |
58 | # Redimensionar para as dimensões finais
59 | return cv2.resize(result, (1080, 1920), interpolation=cv2.INTER_AREA)
60 |
61 | def detect_face_or_body(frame, face_detection, face_mesh, pose):
62 | # Converter a imagem para RGB
63 | frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
64 |
65 | # Processar a detecção de rosto
66 | results_face_detection = face_detection.process(frame_rgb)
67 | results_face_mesh = face_mesh.process(frame_rgb)
68 | results_pose = pose.process(frame_rgb)
69 |
70 | detections = []
71 |
72 | # Usar a detecção de rosto se disponível
73 | if results_face_detection.detections:
74 | # Usar o primeiro rosto detectado
75 | detection = results_face_detection.detections[0]
76 | bbox = detection.location_data.relative_bounding_box
77 | x_min = int(bbox.xmin * frame.shape[1])
78 | y_min = int(bbox.ymin * frame.shape[0])
79 | width = int(bbox.width * frame.shape[1])
80 | height = int(bbox.height * frame.shape[0])
81 | detections.append((x_min, y_min, width, height))
82 |
83 | # Usar landmarks do face mesh se disponível
84 | if results_face_mesh.multi_face_landmarks:
85 | landmarks = results_face_mesh.multi_face_landmarks[0].landmark
86 | # Coordenadas do rosto baseadas nos pontos-chave (landmarks)
87 | x_coords = [int(landmark.x * frame.shape[1]) for landmark in landmarks]
88 | y_coords = [int(landmark.y * frame.shape[0]) for landmark in landmarks]
89 | x_min, x_max = min(x_coords), max(x_coords)
90 | y_min, y_max = min(y_coords), max(y_coords)
91 | width = x_max - x_min
92 | height = y_max - y_min
93 | detections.append((x_min, y_min, width, height))
94 |
95 | # Se nenhum rosto for detectado, usar a pose para estimar o corpo
96 | if results_pose.pose_landmarks:
97 | x_coords = [lmk.x for lmk in results_pose.pose_landmarks.landmark]
98 | y_coords = [lmk.y for lmk in results_pose.pose_landmarks.landmark]
99 | x_min = int(min(x_coords) * frame.shape[1])
100 | x_max = int(max(x_coords) * frame.shape[1])
101 | y_min = int(min(y_coords) * frame.shape[0])
102 | y_max = int(max(y_coords) * frame.shape[0])
103 | width = x_max - x_min
104 | height = y_max - y_min
105 | detections.append((x_min, y_min, width, height))
106 |
107 | # Se nada for detectado, retornar uma lista vazia
108 | return detections if detections else None
109 |
110 |
--------------------------------------------------------------------------------
/scripts/save_json.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 |
4 | def save_viral_segments(segments_data=None):
5 | output_txt_file = "tmp/viral_segments.txt"
6 |
7 | # Verifica se o arquivo já existe
8 | if not os.path.exists(output_txt_file):
9 | if segments_data is None:
10 | # Solicita ao usuário que insira o JSON caso o arquivo não exista e os segmentos não estejam definidos
11 | while True:
12 | user_input = input("\nPor favor, insira o JSON no formato desejado:\n")
13 | try:
14 | # Tenta carregar o JSON inserido
15 | segments_data = json.loads(user_input)
16 |
17 | # Valida se o formato está correto
18 | if "segments" in segments_data and isinstance(segments_data["segments"], list):
19 | # Salva os dados em um arquivo JSON
20 | with open(output_txt_file, 'w', encoding='utf-8') as file:
21 | json.dump(segments_data, file, ensure_ascii=False, indent=4)
22 | print(f"Segmentos virais salvos em {output_txt_file}")
23 | break
24 | else:
25 | print("Formato inválido. Certifique-se de que a estrutura está correta.")
26 | except json.JSONDecodeError:
27 | print("Erro ao decifrar o JSON. Por favor, verifique a formatação.")
28 | print("Por favor, tente novamente.")
29 | else:
30 | # Caso os segmentos tenham sido gerados, salva automaticamente
31 | with open(output_txt_file, 'w', encoding='utf-8') as file:
32 | json.dump(segments_data, file, ensure_ascii=False, indent=4)
33 | print(f"Segmentos virais salvos em {output_txt_file}\n")
34 | else:
35 | print(f"O arquivo {output_txt_file} já existe. Nenhuma entrada adicional é necessária.")
--------------------------------------------------------------------------------
/scripts/transcribe_cuts.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import sys
4 |
5 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
6 |
7 | def transcribe():
8 | def generate_whisperx(input_file, output_folder, model='large-v3'):
9 | output_file = os.path.join(output_folder, f"{os.path.splitext(os.path.basename(input_file))[0]}.srt")
10 | json_file = os.path.join(output_folder, f"{os.path.splitext(os.path.basename(input_file))[0]}.json") # Define the JSON output file
11 |
12 | # Skip processing if the JSON file already exists
13 | if os.path.exists(json_file):
14 | print(f"Arquivo já existe, pulando: {json_file}")
15 | return
16 |
17 | command = [
18 | "whisperx",
19 | input_file,
20 | "--model", model,
21 | "--task", "transcribe",
22 | "--align_model", "WAV2VEC2_ASR_LARGE_LV60K_960H",
23 | "--chunk_size", "10",
24 | "--vad_onset", "0.4",
25 | "--vad_offset", "0.3",
26 | "--compute_type", "float32",
27 | "--batch_size", "10",
28 | "--output_dir", output_folder,
29 | "--output_format", "srt",
30 | "--output_format", "json",
31 | ]
32 |
33 | print(f"Transcrevendo: {input_file}...")
34 | result = subprocess.run(command, shell=True, text=True, capture_output=True)
35 | print(f"Comando executado: {command}")
36 |
37 | if result.returncode != 0:
38 | print("Erro durante a transcrição:")
39 | print(result.stderr)
40 | else:
41 | print(f"Transcrição concluída. Arquivo salvo em: {output_file} e {json_file}")
42 | print(result.stdout) # Verificar a saída correta
43 |
44 | # Define o diretório de entrada e o diretório de saída
45 | input_folder = 'final/'
46 | output_folder = 'subs/'
47 |
48 | # Itera sobre todos os arquivos na pasta de entrada
49 | for filename in os.listdir(input_folder):
50 | if filename.endswith('.mp4'): # Filtra apenas arquivos .mp4
51 | input_file = os.path.join(input_folder, filename)
52 | generate_whisperx(input_file, output_folder)
53 |
54 |
--------------------------------------------------------------------------------
/scripts/transcribe_video.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import os
3 | import sys
4 | import torch
5 | import time
6 |
7 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
8 |
9 | def transcribe(input_file, model='large-v3'):
10 | print(f"Iniciando transcrição de {input_file}...")
11 | start_time = time.time() # Tempo de início da transcrição
12 |
13 | output_folder = 'tmp'
14 | base_name = os.path.splitext(os.path.basename(input_file))[0]
15 | srt_file = os.path.join(output_folder, f"{base_name}.srt")
16 |
17 | # Verifica se o arquivo SRT já existe
18 | if os.path.exists(srt_file):
19 | print(f"O arquivo {srt_file} já existe. Pulando a transcrição.")
20 | return srt_file
21 |
22 | # Verifica se há uma GPU disponível e define o tipo de processamento
23 | if torch.cuda.is_available():
24 | device = "cuda"
25 | print("Placa de vídeo detectada, usando CUDA.")
26 | else:
27 | device = "cpu"
28 | print("Nenhuma placa de vídeo detectada, usando CPU.")
29 |
30 | command = [
31 | "whisperx",
32 | input_file,
33 | "--model", model,
34 | "--task", "transcribe",
35 | "--align_model", "WAV2VEC2_ASR_LARGE_LV60K_960H",
36 | "--interpolate_method", "linear",
37 | "--chunk_size", "10",
38 | "--verbose", "True",
39 | "--vad_onset", "0.4",
40 | "--vad_offset", "0.3",
41 | "--no_align",
42 | "--segment_resolution", "sentence",
43 | "--compute_type", "float32",
44 | "--batch_size", "10",
45 | "--output_dir", output_folder,
46 | "--output_format", "all",
47 | "--device", device # Define o dispositivo baseado na verificação da GPU
48 | ]
49 |
50 | try:
51 | result = subprocess.run(command, check=True, capture_output=True, text=True)
52 | end_time = time.time() # Tempo de término da transcrição
53 | elapsed_time = end_time - start_time # Tempo total de execução
54 |
55 | # Cálculo de minutos e segundos
56 | minutes = int(elapsed_time // 60)
57 | seconds = int(elapsed_time % 60)
58 |
59 | print(f"Transcrição concluída. Saída salva em {srt_file}.")
60 | print(f"Levou {minutes} minutos e {seconds} segundos para transcrever usando {device}.") # Mostra o tempo e o dispositivo
61 | print(result.stdout)
62 | except subprocess.CalledProcessError as e:
63 | print(f"Erro durante a transcrição: {e}")
64 | print(f"Saída de erro: {e.stderr}")
65 | except Exception as e:
66 | print(f"Ocorreu um erro inesperado: {e}")
67 |
68 | # Verifica se o arquivo SRT foi criado
69 | if os.path.exists(srt_file):
70 | print(f"Arquivo SRT {srt_file} criado com sucesso.")
71 | else:
72 | print("Aviso: O arquivo SRT não foi criado como esperado.")
73 |
74 | return srt_file
75 |
--------------------------------------------------------------------------------
/scripts/two_face.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import mediapipe as mp
3 | import numpy as np
4 |
5 | def crop_and_resize_two_faces(frame, face_positions, zoom_out_factor=2.5):
6 | """
7 | Recorta e redimensiona dois rostos detectados no frame, ajustando para uma composição vertical
8 | 1080x1920 onde cada rosto ocupa metade da tela, com um zoom mais afastado.
9 | """
10 | height, width, _ = frame.shape
11 |
12 | # Definir o tamanho da região de cada rosto
13 | crop_width = 1080
14 | crop_height = 960
15 |
16 | # Recortar e redimensionar o primeiro rosto
17 | x1, y1, w1, h1 = face_positions[0]
18 |
19 | # Ajustar o zoom aplicando um fator de afastamento
20 | x1_center = x1 + w1 // 2
21 | y1_center = y1 + h1 // 2
22 | new_w1 = int(w1 * zoom_out_factor)
23 | new_h1 = int(h1 * zoom_out_factor)
24 |
25 | x1_new = max(0, x1_center - new_w1 // 2)
26 | y1_new = max(0, y1_center - new_h1 // 2)
27 |
28 | face1 = frame[max(0, y1_new):min(height, y1_new + new_h1), max(0, x1_new):min(width, x1_new + new_w1)]
29 | face1_resized = cv2.resize(face1, (crop_width, crop_height))
30 |
31 | # Recortar e redimensionar o segundo rosto
32 | x2, y2, w2, h2 = face_positions[1]
33 |
34 | # Ajustar o zoom aplicando o fator de afastamento
35 | x2_center = x2 + w2 // 2
36 | y2_center = y2 + h2 // 2
37 | new_w2 = int(w2 * zoom_out_factor)
38 | new_h2 = int(h2 * zoom_out_factor)
39 |
40 | x2_new = max(0, x2_center - new_w2 // 2)
41 | y2_new = max(0, y2_center - new_h2 // 2)
42 |
43 | face2 = frame[max(0, y2_new):min(height, y2_new + new_h2), max(0, x2_new):min(width, x2_new + new_w2)]
44 | face2_resized = cv2.resize(face2, (crop_width, crop_height))
45 |
46 | # Criar uma tela de 1080x1920 para colocar os dois rostos
47 | result_frame = np.zeros((1920, 1080, 3), dtype=np.uint8)
48 |
49 | # Colocar os rostos na tela: primeiro em cima, segundo embaixo
50 | result_frame[0:960, :] = face1_resized
51 | result_frame[960:1920, :] = face2_resized
52 |
53 | return result_frame
54 |
55 |
56 | def detect_face_or_body_two_faces(frame, face_detection, face_mesh, pose):
57 | # Converter a imagem para RGB
58 | frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
59 |
60 | # Processar a detecção de rosto
61 | results_face_detection = face_detection.process(frame_rgb)
62 | results_face_mesh = face_mesh.process(frame_rgb)
63 | results_pose = pose.process(frame_rgb)
64 |
65 | face_positions = []
66 |
67 | # Usar a detecção de rosto se disponível
68 | if results_face_detection.detections:
69 | for detection in results_face_detection.detections[:2]: # Pegar até 2 rostos
70 | bbox = detection.location_data.relative_bounding_box
71 | x_min = int(bbox.xmin * frame.shape[1])
72 | y_min = int(bbox.ymin * frame.shape[0])
73 | width = int(bbox.width * frame.shape[1])
74 | height = int(bbox.height * frame.shape[0])
75 | face_positions.append((x_min, y_min, width, height))
76 |
77 | if len(face_positions) == 2:
78 | return face_positions
79 |
80 | # Usar landmarks do face mesh se disponível
81 | if results_face_mesh.multi_face_landmarks:
82 | for landmarks in results_face_mesh.multi_face_landmarks[:2]: # Pegar até 2 rostos
83 | x_coords = [int(landmark.x * frame.shape[1]) for landmark in landmarks.landmark]
84 | y_coords = [int(landmark.y * frame.shape[0]) for landmark in landmarks.landmark]
85 | x_min, x_max = min(x_coords), max(x_coords)
86 | y_min, y_max = min(y_coords), max(y_coords)
87 | width = x_max - x_min
88 | height = y_max - y_min
89 | face_positions.append((x_min, y_min, width, height))
90 |
91 | if len(face_positions) == 2:
92 | return face_positions
93 |
94 | # Se nenhum rosto for detectado, usar a pose para estimar o corpo
95 | if results_pose.pose_landmarks:
96 | x_coords = [lmk.x for lmk in results_pose.pose_landmarks.landmark]
97 | y_coords = [lmk.y for lmk in results_pose.pose_landmarks.landmark]
98 | x_min = int(min(x_coords) * frame.shape[1])
99 | x_max = int(max(x_coords) * frame.shape[1])
100 | y_min = int(min(y_coords) * frame.shape[0])
101 | y_max = int(max(y_coords) * frame.shape[0])
102 | width = x_max - x_min
103 | height = y_max - y_min
104 | return [(x_min, y_min, width, height)]
105 |
106 | return None
107 |
108 |
--------------------------------------------------------------------------------