RafaG commited on
Commit
5fa5566
·
verified ·
1 Parent(s): 2bc9209

Upload 24 files

Browse files
.gitignore ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Ignore Visual Studio temporary files, build results, and
2
+ ## files generated by popular Visual Studio add-ons.
3
+ ##
4
+ ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5
+
6
+ # User-specific files
7
+ *.rsuser
8
+ *.suo
9
+ *.user
10
+ *.userosscache
11
+ *.sln.docstates
12
+
13
+ # User-specific files (MonoDevelop/Xamarin Studio)
14
+ *.userprefs
15
+
16
+ # Mono auto generated files
17
+ mono_crash.*
18
+
19
+ # Build results
20
+ [Dd]ebug/
21
+ [Dd]ebugPublic/
22
+ [Rr]elease/
23
+ [Rr]eleases/
24
+ x64/
25
+ x86/
26
+ [Aa][Rr][Mm]/
27
+ [Aa][Rr][Mm]64/
28
+ bld/
29
+ [Bb]in/
30
+ [Oo]bj/
31
+ [Ll]og/
32
+ [Ll]ogs/
33
+
34
+ # Visual Studio 2015/2017 cache/options directory
35
+ .vs/
36
+ # Uncomment if you have tasks that create the project's static files in wwwroot
37
+ #wwwroot/
38
+
39
+ # Visual Studio 2017 auto generated files
40
+ Generated\ Files/
41
+
42
+ # MSTest test Results
43
+ [Tt]est[Rr]esult*/
44
+ [Bb]uild[Ll]og.*
45
+
46
+ # NUnit
47
+ *.VisualState.xml
48
+ TestResult.xml
49
+ nunit-*.xml
50
+
51
+ # Build Results of an ATL Project
52
+ [Dd]ebugPS/
53
+ [Rr]eleasePS/
54
+ dlldata.c
55
+
56
+ # Benchmark Results
57
+ BenchmarkDotNet.Artifacts/
58
+
59
+ # .NET Core
60
+ project.lock.json
61
+ project.fragment.lock.json
62
+ artifacts/
63
+
64
+ # StyleCop
65
+ StyleCopReport.xml
66
+
67
+ # Files built by Visual Studio
68
+ *_i.c
69
+ *_p.c
70
+ *_h.h
71
+ *.ilk
72
+ *.meta
73
+ *.obj
74
+ *.iobj
75
+ *.pch
76
+ *.pdb
77
+ *.ipdb
78
+ *.pgc
79
+ *.pgd
80
+ *.rsp
81
+ *.sbr
82
+ *.tlb
83
+ *.tli
84
+ *.tlh
85
+ *.tmp
86
+ *.tmp_proj
87
+ *_wpftmp.csproj
88
+ *.log
89
+ *.vspscc
90
+ *.vssscc
91
+ .builds
92
+ *.pidb
93
+ *.svclog
94
+ *.scc
95
+
96
+ # Chutzpah Test files
97
+ _Chutzpah*
98
+
99
+ # Visual C++ cache files
100
+ ipch/
101
+ *.aps
102
+ *.ncb
103
+ *.opendb
104
+ *.opensdf
105
+ *.sdf
106
+ *.cachefile
107
+ *.VC.db
108
+ *.VC.VC.opendb
109
+
110
+ # Visual Studio profiler
111
+ *.psess
112
+ *.vsp
113
+ *.vspx
114
+ *.sap
115
+
116
+ # Visual Studio Trace Files
117
+ *.e2e
118
+
119
+ # TFS 2012 Local Workspace
120
+ $tf/
121
+
122
+ # Guidance Automation Toolkit
123
+ *.gpState
124
+
125
+ # ReSharper is a .NET coding add-in
126
+ _ReSharper*/
127
+ *.[Rr]e[Ss]harper
128
+ *.DotSettings.user
129
+
130
+ # TeamCity is a build add-in
131
+ _TeamCity*
132
+
133
+ # DotCover is a Code Coverage Tool
134
+ *.dotCover
135
+
136
+ # AxoCover is a Code Coverage Tool
137
+ .axoCover/*
138
+ !.axoCover/settings.json
139
+
140
+ # Visual Studio code coverage results
141
+ *.coverage
142
+ *.coveragexml
143
+
144
+ # NCrunch
145
+ _NCrunch_*
146
+ .*crunch*.local.xml
147
+ nCrunchTemp_*
148
+
149
+ # MightyMoose
150
+ *.mm.*
151
+ AutoTest.Net/
152
+
153
+ # Web workbench (sass)
154
+ .sass-cache/
155
+
156
+ # Installshield output folder
157
+ [Ee]xpress/
158
+
159
+ # DocProject is a documentation generator add-in
160
+ DocProject/buildhelp/
161
+ DocProject/Help/*.HxT
162
+ DocProject/Help/*.HxC
163
+ DocProject/Help/*.hhc
164
+ DocProject/Help/*.hhk
165
+ DocProject/Help/*.hhp
166
+ DocProject/Help/Html2
167
+ DocProject/Help/html
168
+
169
+ # Click-Once directory
170
+ publish/
171
+
172
+ # Publish Web Output
173
+ *.[Pp]ublish.xml
174
+ *.azurePubxml
175
+ # Note: Comment the next line if you want to checkin your web deploy settings,
176
+ # but database connection strings (with potential passwords) will be unencrypted
177
+ *.pubxml
178
+ *.publishproj
179
+
180
+ # Microsoft Azure Web App publish settings. Comment the next line if you want to
181
+ # checkin your Azure Web App publish settings, but sensitive information contained
182
+ # in these scripts will be unencrypted
183
+ PublishScripts/
184
+
185
+ # NuGet Packages
186
+ *.nupkg
187
+ # NuGet Symbol Packages
188
+ *.snupkg
189
+ # The packages folder can be ignored because of Package Restore
190
+ **/[Pp]ackages/*
191
+ # except build/, which is used as an MSBuild target.
192
+ !**/[Pp]ackages/build/
193
+ # Uncomment if necessary however generally it will be regenerated when needed
194
+ #!**/[Pp]ackages/repositories.config
195
+ # NuGet v3's project.json files produces more ignorable files
196
+ *.nuget.props
197
+ *.nuget.targets
198
+
199
+ # Microsoft Azure Build Output
200
+ csx/
201
+ *.build.csdef
202
+
203
+ # Microsoft Azure Emulator
204
+ ecf/
205
+ rcf/
206
+
207
+ # Windows Store app package directories and files
208
+ AppPackages/
209
+ BundleArtifacts/
210
+ Package.StoreAssociation.xml
211
+ _pkginfo.txt
212
+ *.appx
213
+ *.appxbundle
214
+ *.appxupload
215
+
216
+ # Visual Studio cache files
217
+ # files ending in .cache can be ignored
218
+ *.[Cc]ache
219
+ # but keep track of directories ending in .cache
220
+ !?*.[Cc]ache/
221
+
222
+ # Others
223
+ ClientBin/
224
+ ~$*
225
+ *~
226
+ *.dbmdl
227
+ *.dbproj.schemaview
228
+ *.jfm
229
+ *.pfx
230
+ *.publishsettings
231
+ orleans.codegen.cs
232
+
233
+ # Including strong name files can present a security risk
234
+ # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235
+ #*.snk
236
+
237
+ # Since there are multiple workflows, uncomment next line to ignore bower_components
238
+ # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239
+ #bower_components/
240
+
241
+ # RIA/Silverlight projects
242
+ Generated_Code/
243
+
244
+ # Backup & report files from converting an old project file
245
+ # to a newer Visual Studio version. Backup files are not needed,
246
+ # because we have git ;-)
247
+ _UpgradeReport_Files/
248
+ Backup*/
249
+ UpgradeLog*.XML
250
+ UpgradeLog*.htm
251
+ ServiceFabricBackup/
252
+ *.rptproj.bak
253
+
254
+ # SQL Server files
255
+ *.mdf
256
+ *.ldf
257
+ *.ndf
258
+
259
+ # Business Intelligence projects
260
+ *.rdl.data
261
+ *.bim.layout
262
+ *.bim_*.settings
263
+ *.rptproj.rsuser
264
+ *- [Bb]ackup.rdl
265
+ *- [Bb]ackup ([0-9]).rdl
266
+ *- [Bb]ackup ([0-9][0-9]).rdl
267
+
268
+ # Microsoft Fakes
269
+ FakesAssemblies/
270
+
271
+ # GhostDoc plugin setting file
272
+ *.GhostDoc.xml
273
+
274
+ # Node.js Tools for Visual Studio
275
+ .ntvs_analysis.dat
276
+ node_modules/
277
+
278
+ # Visual Studio 6 build log
279
+ *.plg
280
+
281
+ # Visual Studio 6 workspace options file
282
+ *.opt
283
+
284
+ # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285
+ *.vbw
286
+
287
+ # Visual Studio LightSwitch build output
288
+ **/*.HTMLClient/GeneratedArtifacts
289
+ **/*.DesktopClient/GeneratedArtifacts
290
+ **/*.DesktopClient/ModelManifest.xml
291
+ **/*.Server/GeneratedArtifacts
292
+ **/*.Server/ModelManifest.xml
293
+ _Pvt_Extensions
294
+
295
+ # Paket dependency manager
296
+ .paket/paket.exe
297
+ paket-files/
298
+
299
+ # FAKE - F# Make
300
+ .fake/
301
+
302
+ # CodeRush personal settings
303
+ .cr/personal
304
+
305
+ # Python Tools for Visual Studio (PTVS)
306
+ __pycache__/
307
+ *.pyc
308
+
309
+ # Cake - Uncomment if you are using it
310
+ # tools/**
311
+ # !tools/packages.config
312
+
313
+ # Tabs Studio
314
+ *.tss
315
+
316
+ # Telerik's JustMock configuration file
317
+ *.jmconfig
318
+
319
+ # BizTalk build output
320
+ *.btp.cs
321
+ *.btm.cs
322
+ *.odx.cs
323
+ *.xsd.cs
324
+
325
+ # OpenCover UI analysis results
326
+ OpenCover/
327
+
328
+ # Azure Stream Analytics local run output
329
+ ASALocalRun/
330
+
331
+ # MSBuild Binary and Structured Log
332
+ *.binlog
333
+
334
+ # NVidia Nsight GPU debugger configuration file
335
+ *.nvuser
336
+
337
+ # MFractors (Xamarin productivity tool) working folder
338
+ .mfractor/
339
+
340
+ # Local History for Visual Studio
341
+ .localhistory/
342
+
343
+ # BeatPulse healthcheck temp database
344
+ healthchecksdb
345
+
346
+ # Backup folder for Package Reference Convert tool in Visual Studio 2017
347
+ MigrationBackup/
348
+
349
+ # Ionide (cross platform F# VS Code tools) working folder
350
+ .ionide/
351
+
352
+ vidqa_data/
353
+ media/
354
+ temp/
355
+ legen_burned_*/
356
+ legen_srt_*/
357
+ log-vidqa.txt
358
+ legen_errors.txt
359
+ legen-errors.txt
360
+ .vscode/launch.json
361
+
362
+ **.srt
363
+ **.mp4
364
+ **.webm
365
+ **.mkv
366
+ **.avi
367
+ **.mov
368
+ **.wmv
369
+ **.flv
370
+ **.vob
371
+ **.mts
372
+ **.m2ts
373
+ **.ts
374
+ **.yuv
375
+ **.mpg
376
+ **.mpga
377
+ **.mp2
378
+ **.mpeg
379
+ **.mpe
380
+ **.mpv
381
+ **.m2v
382
+ **.m4v
383
+ **.3gp
384
+ **.3g2
385
+ **.nsv
386
+ **.aa
387
+ **.aac
388
+ **.aax
389
+ **.act
390
+ **.aiff
391
+ **.alac
392
+ **.amr
393
+ **.ape
394
+ **.au
395
+ **.awb
396
+ **.dss
397
+ **.dvf
398
+ **.flac
399
+ **.gsm
400
+ **.iklax
401
+ **.ivs
402
+ **.m4a
403
+ **.m4b
404
+ **.m4p
405
+ **.mmf
406
+ **.mp3
407
+ **.mpc
408
+ **.msv
409
+ **.nmf
410
+ **.ogg
411
+ **.oga
412
+ **.mogg
413
+ **.opus
414
+ **.ra
415
+ **.rm
416
+ **.raw
417
+ **.rf64
418
+ **.sln
419
+ **.tta
420
+ **.voc
421
+ **.vox
422
+ **.wav
423
+ **.wma
424
+ **.wv
425
+ **.webm
426
+ **.8svx
427
+ **.mts
LICENSE ADDED
@@ -0,0 +1,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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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
+ <program> Copyright (C) <year> <name of author>
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
+ <https://www.gnu.org/licenses/>.
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
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,13 +1,152 @@
1
- ---
2
- title: Lege
3
- emoji: 🌍
4
- colorFrom: pink
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.0.1
8
- app_file: app.py
9
- pinned: false
10
- license: gpl-3.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LeGen
2
+
3
+ ![legen-wide](https://github.com/matheusbach/legen/assets/35426162/05a7acd2-52d5-43e0-8f31-7da7d6aa7c3c)
4
+
5
+
6
+ LeGen is a Python script that uses Whisper/WhisperX AI to locally transcribes speech from media files, generating subtitle files, can translates the generated subtitles, inserts them into the mp4 container, and burns them directly into video
7
+
8
+ This is very useful for making it available in another language, or even just subtitling any video that belongs to you or that you have the proper authorization to do so, be it a film, lecture, course, presentation, interview, etc.
9
+
10
+ ## Run on Colab
11
+
12
+ LeGen works on Google Colab, using their computing power to do the work. Aceess the link to [run on Google Colab](https://colab.research.google.com/github/matheusbach/legen/blob/main/legen.ipynb)
13
+
14
+ <a href='https://colab.research.google.com/github/matheusbach/legen/blob/main/legen.ipynb' style='padding-left: 0.5rem;'><img src='https://colab.research.google.com/assets/colab-badge.svg' alt='Google Colab'></a>
15
+
16
+ ## Install locally:
17
+
18
+ Install FFMpeg from [FFMPeg Oficial Site](https://ffmpeg.org/download.html) or from your linux package manager. _If using windows, prefer gyan_dev release full `choco install ffmpeg-full`_
19
+
20
+ Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
21
+
22
+ Install [Python](https://www.python.org/downloads/) 3.8 or up. _If using windows, select "Add to PATH" option when installing_
23
+
24
+ Clone LeGen using git
25
+ ```sh
26
+ git clone https://github.com/matheusbach/legen.git
27
+ cd legen
28
+ ```
29
+
30
+ Install requirements using pip. Is recommended to create a virtual environment (venv) as a good practice
31
+ ```sh
32
+ pip3 install -r requirements.txt --upgrade
33
+ ```
34
+
35
+ ### GPU compatibility
36
+
37
+ If having troubles with GPU compatibility, get [PyTorch](https://pytorch.org/get-started/locally/) for your GPU.
38
+
39
+ _And done. Now you can use LeGen_
40
+
41
+ ### Update
42
+
43
+ For dry-run update, use in legen folder:
44
+ ```sh
45
+ git fetch && git reset --hard origin/main && git pull
46
+ pip3 install -r requirements.txt --upgrade --force-reinstall
47
+ ```
48
+
49
+ ## Run locally:
50
+
51
+ To use LeGen, run the following command:
52
+
53
+ The minimum comand line is:
54
+
55
+ ```sh
56
+ python3 legen.py -i [input_path]
57
+ ```
58
+
59
+ Users could for example also translate generated subtitles for other language like portuguese (pt) adding `--translate pt` to the command line
60
+
61
+
62
+ Full options list are described bellow:
63
+
64
+ - `-i`, `--input_path`: Specifies the path to the media files. This can be a folder containing files or an individual file. Example: `LeGen -i /path/to/media/files`.
65
+
66
+ - `--norm`: Normalizes folder times and runs vidqa on the input path before starting to process files. Useful for synchronizing timestamps across multiple media files.
67
+
68
+ - `-ts:e`, `--transcription_engine`: Specifies the transcription engine to use. Possible values are "whisperx" and "whisper". Default is "whisperx".
69
+
70
+ - `-ts:m`, `--transcription_model`: Specifies the path or name of the Whisper transcription model. A larger model will consume more resources and be slower, but with better transcription quality. Possible values: tiny, base, small, medium (default), large, ...
71
+
72
+ - `-ts:d`, `--transcription_device`: Specifies the device to run the transcription through Whisper. Possible values: auto (default), cpu, cuda.
73
+
74
+ - `-ts:c`, `--transcription_compute_type`: Specifies the quantization for the neural network. Possible values: auto (default), int8, int8_float32, int8_float16, int8_bfloat16, int16, float16, bfloat16, float32.
75
+
76
+ - `-ts:b`, `--transcription_batch`: Specifies the number of simultaneous segments being transcribed. Higher values will speed up processing. If you have low RAM/VRAM, long duration media files or have buggy subtitles, reduce this value to avoid issues. Only works using transcription_engine whisperx. Default is 4.
77
+
78
+ - `--translate`: Translates subtitles to a language code if they are not the same as the original. The language code should be specified after the equals sign. For example, `LeGen --translate=fr` would translate the subtitles to French.
79
+
80
+ - `--input_lang`: Indicates (forces) the language of the voice in the input media. Default is "auto".
81
+
82
+ - `-c:v`, `--codec_video`: Specifies the target video codec. Can be used to set acceleration via GPU or another video API [codec_api], if supported (ffmpeg -encoders). Examples include h264, libx264, h264_vaapi, h264_nvenc, hevc, libx265 hevc_vaapi, hevc_nvenc, hevc_cuvid, hevc_qsv, hevc_amf. Default is h264.
83
+
84
+ - `-c:a`, `--codec_audio`: Specifies the target audio codec. Default is aac. Examples include aac, libopus, mp3, vorbis.
85
+
86
+ - `-o:s`, `--output_softsubs`: Specifies the path to the folder or output file for the video files with embedded softsub (embedded in the mp4 container and .srt files). Default is "softsubs_" followed by the input path.
87
+
88
+ - `-o:h`, `--output_hardsubs`: Specifies the output folder path for video files with burned-in captions and embedded in the mp4 container. Default is "hardsubs_" followed by the input path.
89
+
90
+ - `--overwrite`: Overwrites existing files in output directories. By default, this option is false.
91
+
92
+ - `--disable_srt`: Disables .srt file generation and doesn't insert subtitles in the mp4 container of output_softsubs. By default, this option is false.
93
+
94
+ - `--disable_softsubs`: Doesn't insert subtitles in the mp4 container of output_softsubs. This option continues generating .srt files. By default, this option is false.
95
+
96
+ - `--disable_hardsubs`: Disables subtitle burn in output_hardsubs. By default, this option is false.
97
+
98
+ - `--copy_files`: Copies other (non-video) files present in the input directory to output directories. Only generates the subtitles and videos. By default, this option is false.
99
+
100
+ Each of these options provides control over various aspects of the video processing workflow. Make sure to refer to the documentation or help message (`LeGen --help`) for more details on each option[Source 0](https://docs.python.org/3/library/argparse.html)[Source 2](https://realpython.com/command-line-interfaces-python-argparse/).
101
+
102
+ ## Dependencies
103
+
104
+ LeGen requires the following **pip** dependencies to be installed:
105
+ - deep_translator
106
+ - ffmpeg_progress_yield
107
+ - openai_whisper
108
+ - pysrt
109
+ - torch
110
+ - tqdm
111
+ - whisper
112
+ - vidqa
113
+ - matheusbach/whisperx (fork from m-bain/whisperx)
114
+
115
+ This dependencies can be installed and updated with ```pip install -r requirements.txt --upgrade```
116
+
117
+ You also need to [install FFmpeg](https://ffmpeg.org/download.html)
118
+
119
+ ## Contributing
120
+
121
+ Contributions are welcome. Submit your pull request ❤️
122
+
123
+ ## Issues, Doubts
124
+
125
+ Not being able to use the software, or encountering an error? open an [issue](https://github.com/matheusbach/legen/issues/new)
126
+
127
+ ## Telegram Group
128
+
129
+ Welcome and don't be a sick. We are brazilian, but you can write in other language if you want. https://t.me/+c0VRonlcd9Q2YTAx
130
+
131
+ ## Video Tutorials
132
+
133
+ [PT-BR] [SEMI-OUTDATED] [**Tutorial - LeGen no Google Colab**](https://odysee.com/@legen_software:d/legen_no_colab:0)
134
+
135
+ ## Donations
136
+
137
+ You can donate to project using:
138
+ Monero (XMR): ```86HjTCsiaELEoNhH96rTf3ezGMXgKmHjqFrNmca2tesCESdCTZvRvQ9QWQXPGDtmaZhKz4ryHCdZXFzdbmtGahVa5VMLJnx```
139
+ LivePix: https://livepix.gg/legendonate
140
+
141
+ ### Donators
142
+ - Picasso Neves
143
+ - Erasmo de Souza Mora
144
+ - viniciuspro
145
+ - Igor
146
+ - NiNi
147
+ - PopularC
148
+
149
+
150
+ ## License
151
+
152
+ This project is licensed under the terms of the [GNU GPLv3](https://choosealicense.com/licenses/gpl-3.0/).
app.py CHANGED
@@ -1 +1,315 @@
1
- print('test')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ import asyncio
6
+ import threading
7
+ import signal
8
+ import sys
9
+ import re
10
+ from typing import Optional, List
11
+ from i18n.i18n import I18nAuto
12
+ from header import badges, description
13
+ i18n = I18nAuto()
14
+
15
+ # Variável global para armazenar o processo atual
16
+ current_process: Optional[subprocess.Popen] = None
17
+
18
+ # Força o uso de UTF-8 para o Python
19
+ os.environ["PYTHONIOENCODING"] = "utf-8"
20
+
21
+ # Para garantir que a codificação esteja correta no terminal
22
+ if sys.platform == "win32":
23
+ os.system('chcp 65001')
24
+
25
+ # Redefine a configuração de codificação da saída padrão
26
+ sys.stdout.reconfigure(encoding='utf-8')
27
+ sys.stderr.reconfigure(encoding='utf-8')
28
+
29
+ def clean_ansi(text: str) -> str:
30
+ """Remove códigos ANSI e limpa o texto para exibição"""
31
+ ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
32
+ return ansi_escape.sub('', text)
33
+
34
+ def process_output(line: str, progress: gr.Progress) -> str:
35
+ """Processa uma linha de saída e atualiza o progresso"""
36
+ clean_line = clean_ansi(line.strip())
37
+
38
+ # Procura por padrões de progresso
39
+ if "%" in clean_line:
40
+ try:
41
+ # Extrai o número do progresso
42
+ progress_match = re.search(r'(\d+\.?\d*)%', clean_line)
43
+ if progress_match:
44
+ progress_value = float(progress_match.group(1)) / 100
45
+ progress(progress_value, desc=clean_line)
46
+ except ValueError:
47
+ pass
48
+
49
+ return clean_line
50
+
51
+ def stop_process():
52
+ global current_process
53
+ if current_process:
54
+ try:
55
+ if os.name == 'nt':
56
+ current_process.terminate()
57
+ else:
58
+ os.killpg(os.getpgid(current_process.pid), signal.SIGTERM)
59
+ current_process.wait(timeout=5) # Espera até 5 segundos pelo término
60
+ except subprocess.TimeoutExpired:
61
+ if os.name == 'nt':
62
+ current_process.kill()
63
+ else:
64
+ os.killpg(os.getpgid(current_process.pid), signal.SIGKILL)
65
+ current_process = None
66
+ return "Process stopped by user"
67
+ return "No process running"
68
+
69
+ def run_legen(
70
+ input_path,
71
+ transcription_engine,
72
+ transcription_model,
73
+ compute_type,
74
+ device,
75
+ batch_size,
76
+ input_lang,
77
+ translate_lang,
78
+ video_codec,
79
+ audio_codec,
80
+ output_softsubs_path,
81
+ output_hardsubs_path,
82
+ normalize,
83
+ overwrite,
84
+ copy_files,
85
+ disable_srt,
86
+ disable_softsubs,
87
+ disable_hardsubs,
88
+ progress=gr.Progress()
89
+ ):
90
+ global current_process
91
+
92
+ if not input_path:
93
+ return "Please provide an input path"
94
+
95
+ if not os.path.exists(input_path):
96
+ return "Input path does not exist"
97
+
98
+ if not os.path.exists("legen.py"):
99
+ return "legen.py not found in current directory"
100
+
101
+ cmd = ["python", "legen.py", "-i", input_path]
102
+
103
+ # Adiciona as flags baseadas nos checkboxes
104
+ if normalize: cmd.append("--norm")
105
+ if overwrite: cmd.append("--overwrite")
106
+ if copy_files: cmd.append("--copy_files")
107
+ if disable_srt: cmd.append("--disable_srt")
108
+ if disable_softsubs: cmd.append("--disable_softsubs")
109
+ if disable_hardsubs: cmd.append("--disable_hardsubs")
110
+
111
+ # Adiciona configurações de transcrição
112
+ cmd.extend(["-ts:e", transcription_engine])
113
+ cmd.extend(["-ts:m", transcription_model])
114
+ cmd.extend(["-ts:d", device])
115
+ cmd.extend(["-ts:c", compute_type])
116
+ cmd.extend(["-ts:b", str(batch_size)])
117
+
118
+ if translate_lang != "none":
119
+ cmd.extend(["--translate", translate_lang])
120
+ if input_lang != "auto":
121
+ cmd.extend(["--input_lang", input_lang])
122
+
123
+ # Adiciona configurações de codec
124
+ cmd.extend(["-c:v", video_codec])
125
+ cmd.extend(["-c:a", audio_codec])
126
+
127
+ # Adiciona caminhos de saída
128
+ if output_softsubs_path:
129
+ cmd.extend(["-o:s", output_softsubs_path])
130
+ if output_hardsubs_path:
131
+ cmd.extend(["-o:h", output_hardsubs_path])
132
+
133
+ try:
134
+ startupinfo = None
135
+ if os.name == 'nt':
136
+ startupinfo = subprocess.STARTUPINFO()
137
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
138
+
139
+ current_process = subprocess.Popen(
140
+ cmd,
141
+ stdout=subprocess.PIPE,
142
+ stderr=subprocess.STDOUT, # Combina stderr com stdout
143
+ text=True,
144
+ bufsize=1,
145
+ universal_newlines=True,
146
+ startupinfo=startupinfo,
147
+ encoding='utf-8',
148
+ errors='replace',
149
+ preexec_fn=None if os.name == 'nt' else os.setsid
150
+ )
151
+
152
+ output_lines: List[str] = []
153
+ last_progress_update = 0
154
+
155
+ while True:
156
+ line = current_process.stdout.readline()
157
+
158
+ if not line and current_process.poll() is not None:
159
+ break
160
+
161
+ if line:
162
+ try:
163
+ clean_line = process_output(line, progress)
164
+ output_lines.append(clean_line)
165
+
166
+ # Atualiza a saída periodicamente
167
+ if len(output_lines) - last_progress_update >= 5:
168
+ yield "\n".join(output_lines)
169
+ last_progress_update = len(output_lines)
170
+
171
+ except Exception as e:
172
+ output_lines.append(f"Error processing output: {str(e)}")
173
+
174
+ if current_process.poll() == 0:
175
+ final_output = "Processing completed successfully!\n\n" + "\n".join(output_lines)
176
+ else:
177
+ final_output = f"Process ended with error code {current_process.poll()}\n\n" + "\n".join(output_lines)
178
+
179
+ current_process = None
180
+ return final_output
181
+
182
+ except Exception as e:
183
+ current_process = None
184
+ return f"Error: {str(e)}"
185
+
186
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
187
+ gr.Markdown(badges)
188
+ gr.Markdown(description)
189
+ title="LeGen"
190
+
191
+ with gr.Row():
192
+ with gr.Column():
193
+ # Input Section
194
+ with gr.Group():
195
+ input_path = gr.Textbox(label=i18n("Input Path"), placeholder=i18n("Enter path to file or folder"))
196
+
197
+ # Transcription Settings
198
+ with gr.Group():
199
+ transcription_engine = gr.Dropdown(
200
+ choices=["whisperx", "whisper"],
201
+ value="whisperx",
202
+ label=i18n("Transcription Engine")
203
+ )
204
+ with gr.Row():
205
+ transcription_model = gr.Dropdown(
206
+ choices=["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo",],
207
+ value="large-v3",
208
+ label=i18n("Model")
209
+ )
210
+ compute_type = gr.Dropdown(
211
+ choices=["auto", "int8", "float16", "float32"],
212
+ value="auto",
213
+ label=i18n("Compute Type")
214
+ )
215
+ with gr.Row():
216
+ device = gr.Dropdown(
217
+ choices=["auto", "cpu", "cuda"],
218
+ value="auto",
219
+ label=i18n("Device")
220
+ )
221
+ batch_size = gr.Number(
222
+ value=4,
223
+ label=i18n("Batch Size"),
224
+ precision=0
225
+ )
226
+ with gr.Row():
227
+ input_lang = gr.Dropdown(
228
+ choices=["auto", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
229
+ value="auto",
230
+ label=i18n("Input Language")
231
+ )
232
+ translate_lang = gr.Dropdown(
233
+ choices=["none", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
234
+ value="none",
235
+ label=i18n("Translate to")
236
+ )
237
+
238
+ with gr.Column():
239
+ # Output Settings
240
+ with gr.Group():
241
+ with gr.Row():
242
+ video_codec = gr.Dropdown(
243
+ choices=["h264", "libx264", "h264_vaapi", "h264_nvenc", "hevc", "libx265", "hevc_vaapi"],
244
+ value="h264",
245
+ label=i18n("Video Codec")
246
+ )
247
+ audio_codec = gr.Dropdown(
248
+ choices=["aac", "libopus", "mp3", "vorbis"],
249
+ value="aac",
250
+ label=i18n("Audio Codec")
251
+ )
252
+ output_softsubs_path = gr.Textbox(
253
+ value="softsubs_output",
254
+ label=i18n("Softsubs Output Path")
255
+ )
256
+ output_hardsubs_path = gr.Textbox(
257
+ value="hardsubs_output",
258
+ label=i18n("Hardsubs Output Path")
259
+ )
260
+
261
+ # Options
262
+ with gr.Group():
263
+ with gr.Row():
264
+ normalize = gr.Checkbox(label=i18n("Normalize folder times"), value=False)
265
+ overwrite = gr.Checkbox(label=i18n("Overwrite existing files"), value=False)
266
+ copy_files = gr.Checkbox(label=i18n("Copy non-video files"), value=False)
267
+ with gr.Row():
268
+ disable_srt = gr.Checkbox(label=i18n("Disable SRT generation"), value=False)
269
+ disable_softsubs = gr.Checkbox(label=i18n("Disable softsubs"), value=False)
270
+ disable_hardsubs = gr.Checkbox(label=i18n("Disable hardsubs"), value=False)
271
+
272
+ # Run Button, Stop Button and Output
273
+ with gr.Row():
274
+ with gr.Column():
275
+ run_btn = gr.Button(i18n("Run LeGen"), variant="primary")
276
+ stop_btn = gr.Button(i18n("Stop"), variant="stop")
277
+ output = gr.Textbox(label=i18n("Output"), lines=5)
278
+
279
+ # Connect the run button to the processing function
280
+ run_btn.click(
281
+ fn=run_legen,
282
+ inputs=[
283
+ input_path,
284
+ transcription_engine,
285
+ transcription_model,
286
+ compute_type,
287
+ device,
288
+ batch_size,
289
+ input_lang,
290
+ translate_lang,
291
+ video_codec,
292
+ audio_codec,
293
+ output_softsubs_path,
294
+ output_hardsubs_path,
295
+ normalize,
296
+ overwrite,
297
+ copy_files,
298
+ disable_srt,
299
+ disable_softsubs,
300
+ disable_hardsubs
301
+ ],
302
+ outputs=output
303
+ )
304
+
305
+ stop_btn.click(
306
+ fn=stop_process,
307
+ inputs=[],
308
+ outputs=output
309
+ )
310
+ gr.Markdown("""
311
+ <center>WebUI Desenvolvida por Rafa.Godoy</center>
312
+ <center>Agradecimentos ao MatheusBach por desenvolver o LeGen</center>
313
+ """)
314
+ if __name__ == "__main__":
315
+ demo.launch()
app_hf.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ import asyncio
6
+ import threading
7
+ import signal
8
+ import sys
9
+ import re
10
+ import shutil
11
+ from typing import Optional, List, Tuple
12
+ from i18n.i18n import I18nAuto
13
+ from header import badges, description
14
+ i18n = I18nAuto()
15
+
16
+ # Variável global para armazenar o processo atual
17
+ current_process: Optional[subprocess.Popen] = None
18
+
19
+ # Força o uso de UTF-8 para o Python
20
+ os.environ["PYTHONIOENCODING"] = "utf-8"
21
+
22
+ # Para garantir que a codificação esteja correta no terminal
23
+ if sys.platform == "win32":
24
+ os.system('chcp 65001')
25
+
26
+ # Redefine a configuração de codificação da saída padrão
27
+ sys.stdout.reconfigure(encoding='utf-8')
28
+ sys.stderr.reconfigure(encoding='utf-8')
29
+
30
+ # Criar diretórios necessários se não existirem
31
+ def ensure_directories():
32
+ directories = ['uploaded_videos', 'softsubs_output', 'hardsubs_output']
33
+ for directory in directories:
34
+ os.makedirs(os.path.join(os.getcwd(), directory), exist_ok=True)
35
+ return os.path.join(os.getcwd(), 'uploaded_videos')
36
+
37
+ def save_uploaded_files(files):
38
+ """Salva os arquivos enviados na pasta uploaded_videos"""
39
+ if not files:
40
+ return "No files uploaded"
41
+
42
+ upload_dir = ensure_directories()
43
+ saved_files = []
44
+
45
+ for file in files:
46
+ filename = os.path.basename(file.name)
47
+ destination = os.path.join(upload_dir, filename)
48
+ shutil.copy2(file.name, destination)
49
+ saved_files.append(filename)
50
+
51
+ return f"Uploaded files: {', '.join(saved_files)}"
52
+
53
+ def get_output_files() -> Tuple[List[str], List[str]]:
54
+ """Retorna listas de arquivos nas pastas de saída"""
55
+ softsubs_dir = os.path.join(os.getcwd(), 'softsubs_output')
56
+ hardsubs_dir = os.path.join(os.getcwd(), 'hardsubs_output')
57
+
58
+ softsubs_files = [os.path.join(softsubs_dir, f) for f in os.listdir(softsubs_dir) if os.path.isfile(os.path.join(softsubs_dir, f))]
59
+ hardsubs_files = [os.path.join(hardsubs_dir, f) for f in os.listdir(hardsubs_dir) if os.path.isfile(os.path.join(hardsubs_dir, f))]
60
+
61
+ return softsubs_files, hardsubs_files
62
+
63
+ def clean_ansi(text: str) -> str:
64
+ """Remove códigos ANSI e limpa o texto para exibição"""
65
+ ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
66
+ return ansi_escape.sub('', text)
67
+
68
+ def process_output(line: str, progress: gr.Progress) -> str:
69
+ """Processa uma linha de saída e atualiza o progresso"""
70
+ clean_line = clean_ansi(line.strip())
71
+
72
+ if "%" in clean_line:
73
+ try:
74
+ progress_match = re.search(r'(\d+\.?\d*)%', clean_line)
75
+ if progress_match:
76
+ progress_value = float(progress_match.group(1)) / 100
77
+ progress(progress_value, desc=clean_line)
78
+ except ValueError:
79
+ pass
80
+
81
+ return clean_line
82
+
83
+ def stop_process():
84
+ global current_process
85
+ if current_process:
86
+ try:
87
+ if os.name == 'nt':
88
+ current_process.terminate()
89
+ else:
90
+ os.killpg(os.getpgid(current_process.pid), signal.SIGTERM)
91
+ current_process.wait(timeout=5)
92
+ except subprocess.TimeoutExpired:
93
+ if os.name == 'nt':
94
+ current_process.kill()
95
+ else:
96
+ os.killpg(os.getpgid(current_process.pid), signal.SIGKILL)
97
+ current_process = None
98
+ return "Process stopped by user"
99
+ return "No process running"
100
+
101
+ def run_legen(
102
+ transcription_engine,
103
+ transcription_model,
104
+ compute_type,
105
+ device,
106
+ batch_size,
107
+ input_lang,
108
+ translate_lang,
109
+ video_codec,
110
+ audio_codec,
111
+ normalize,
112
+ overwrite,
113
+ copy_files,
114
+ disable_srt,
115
+ disable_softsubs,
116
+ disable_hardsubs,
117
+ progress=gr.Progress()
118
+ ):
119
+ global current_process
120
+
121
+ input_dir = ensure_directories()
122
+ if not os.path.exists(input_dir) or not os.listdir(input_dir):
123
+ return "No files found in uploaded_videos directory"
124
+
125
+ if not os.path.exists("legen.py"):
126
+ return "legen.py not found in current directory"
127
+
128
+ cmd = ["python", "legen.py", "-i", input_dir]
129
+
130
+ # Adiciona as flags baseadas nos checkboxes
131
+ if normalize: cmd.append("--norm")
132
+ if overwrite: cmd.append("--overwrite")
133
+ if copy_files: cmd.append("--copy_files")
134
+ if disable_srt: cmd.append("--disable_srt")
135
+ if disable_softsubs: cmd.append("--disable_softsubs")
136
+ if disable_hardsubs: cmd.append("--disable_hardsubs")
137
+
138
+ # Adiciona configurações de transcrição
139
+ cmd.extend(["-ts:e", transcription_engine])
140
+ cmd.extend(["-ts:m", transcription_model])
141
+ cmd.extend(["-ts:d", device])
142
+ cmd.extend(["-ts:c", compute_type])
143
+ cmd.extend(["-ts:b", str(batch_size)])
144
+
145
+ if translate_lang != "none":
146
+ cmd.extend(["--translate", translate_lang])
147
+ if input_lang != "auto":
148
+ cmd.extend(["--input_lang", input_lang])
149
+
150
+ # Adiciona configurações de codec
151
+ cmd.extend(["-c:v", video_codec])
152
+ cmd.extend(["-c:a", audio_codec])
153
+
154
+ # Adiciona caminhos de saída fixos
155
+ cmd.extend(["-o:s", os.path.join(os.getcwd(), "softsubs_output")])
156
+ cmd.extend(["-o:h", os.path.join(os.getcwd(), "hardsubs_output")])
157
+
158
+ try:
159
+ startupinfo = None
160
+ if os.name == 'nt':
161
+ startupinfo = subprocess.STARTUPINFO()
162
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
163
+
164
+ current_process = subprocess.Popen(
165
+ cmd,
166
+ stdout=subprocess.PIPE,
167
+ stderr=subprocess.STDOUT,
168
+ text=True,
169
+ bufsize=1,
170
+ universal_newlines=True,
171
+ startupinfo=startupinfo,
172
+ encoding='utf-8',
173
+ errors='replace',
174
+ preexec_fn=None if os.name == 'nt' else os.setsid
175
+ )
176
+
177
+ output_lines: List[str] = []
178
+ last_progress_update = 0
179
+
180
+ while True:
181
+ line = current_process.stdout.readline()
182
+
183
+ if not line and current_process.poll() is not None:
184
+ break
185
+
186
+ if line:
187
+ try:
188
+ clean_line = process_output(line, progress)
189
+ output_lines.append(clean_line)
190
+
191
+ if len(output_lines) - last_progress_update >= 5:
192
+ yield "\n".join(output_lines)
193
+ last_progress_update = len(output_lines)
194
+
195
+ except Exception as e:
196
+ output_lines.append(f"Error processing output: {str(e)}")
197
+
198
+ if current_process.poll() == 0:
199
+ final_output = "Processing completed successfully!\n\n" + "\n".join(output_lines)
200
+ else:
201
+ final_output = f"Process ended with error code {current_process.poll()}\n\n" + "\n".join(output_lines)
202
+
203
+ current_process = None
204
+ return final_output
205
+
206
+ except Exception as e:
207
+ current_process = None
208
+ return f"Error: {str(e)}"
209
+
210
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
211
+ gr.Markdown(badges)
212
+ gr.Markdown(description)
213
+ title = "LeGen"
214
+
215
+ ensure_directories() # Garante que os diretórios existam ao iniciar
216
+
217
+ with gr.Row():
218
+ with gr.Column(scale=1):
219
+ # Upload Section
220
+ with gr.Group():
221
+ upload_files = gr.Files(
222
+ label=i18n("Upload Videos"),
223
+ file_types=["video"],
224
+ file_count="multiple"
225
+ )
226
+ upload_button = gr.Button(i18n("Upload to processing directory"))
227
+
228
+ # Transcription Settings
229
+ with gr.Group():
230
+ transcription_engine = gr.Dropdown(
231
+ choices=["whisperx", "whisper"],
232
+ value="whisperx",
233
+ label=i18n("Transcription Engine")
234
+ )
235
+ with gr.Row():
236
+ transcription_model = gr.Dropdown(
237
+ choices=["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo"],
238
+ value="large-v3",
239
+ label=i18n("Model")
240
+ )
241
+ compute_type = gr.Dropdown(
242
+ choices=["auto", "int8", "float16", "float32"],
243
+ value="auto",
244
+ label=i18n("Compute Type")
245
+ )
246
+ with gr.Row():
247
+ device = gr.Dropdown(
248
+ choices=["auto", "cpu", "cuda"],
249
+ value="auto",
250
+ label=i18n("Device")
251
+ )
252
+ batch_size = gr.Number(
253
+ value=4,
254
+ label=i18n("Batch Size"),
255
+ precision=0
256
+ )
257
+ with gr.Row():
258
+ input_lang = gr.Dropdown(
259
+ choices=["auto", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
260
+ value="auto",
261
+ label=i18n("Input Language")
262
+ )
263
+ translate_lang = gr.Dropdown(
264
+ choices=["none", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
265
+ value="none",
266
+ label=i18n("Translate to")
267
+ )
268
+
269
+ with gr.Column(scale=1):
270
+ # Output Settings
271
+ with gr.Group():
272
+ with gr.Row():
273
+ video_codec = gr.Dropdown(
274
+ choices=["h264", "libx264", "h264_vaapi", "h264_nvenc", "hevc", "libx265", "hevc_vaapi"],
275
+ value="h264",
276
+ label=i18n("Video Codec")
277
+ )
278
+ audio_codec = gr.Dropdown(
279
+ choices=["aac", "libopus", "mp3", "vorbis"],
280
+ value="aac",
281
+ label=i18n("Audio Codec")
282
+ )
283
+
284
+ # Options
285
+ with gr.Group():
286
+ with gr.Row():
287
+ normalize = gr.Checkbox(label=i18n("Normalize folder times"), value=False)
288
+ overwrite = gr.Checkbox(label=i18n("Overwrite existing files"), value=False)
289
+ copy_files = gr.Checkbox(label=i18n("Copy non-video files"), value=False)
290
+ with gr.Row():
291
+ disable_srt = gr.Checkbox(label=i18n("Disable SRT generation"), value=False)
292
+ disable_softsubs = gr.Checkbox(label=i18n("Disable softsubs"), value=False)
293
+ disable_hardsubs = gr.Checkbox(label=i18n("Disable hardsubs"), value=False)
294
+
295
+ # Output Files Display
296
+ with gr.Group():
297
+ softsubs_files = gr.Files(label="Softsubs Output Files", file_count="multiple", interactive=False)
298
+ hardsubs_files = gr.Files(label="Hardsubs Output Files", file_count="multiple", interactive=False)
299
+
300
+ # Run Button, Stop Button and Output
301
+ with gr.Row():
302
+ with gr.Column(scale=1):
303
+ run_btn = gr.Button(i18n("Run LeGen"), variant="primary")
304
+ stop_btn = gr.Button(i18n("Stop"), variant="stop")
305
+ output = gr.Textbox(label=i18n("Output"), lines=2, interactive=False, elem_id="output")
306
+
307
+ # Event handlers
308
+ upload_button.click(
309
+ fn=save_uploaded_files,
310
+ inputs=[upload_files],
311
+ outputs=[output]
312
+ )
313
+
314
+ def update_output_files():
315
+ softsubs_files, hardsubs_files = get_output_files()
316
+ return softsubs_files, hardsubs_files
317
+
318
+ # Connect the run button to the processing function
319
+ run_btn.click(
320
+ fn=run_legen,
321
+ inputs=[
322
+ transcription_engine,
323
+ transcription_model,
324
+ compute_type,
325
+ device,
326
+ batch_size,
327
+ input_lang,
328
+ translate_lang,
329
+ video_codec,
330
+ audio_codec,
331
+ normalize,
332
+ overwrite,
333
+ copy_files,
334
+ disable_srt,
335
+ disable_softsubs,
336
+ disable_hardsubs
337
+ ],
338
+ outputs=output
339
+ ).then(
340
+ fn=update_output_files,
341
+ inputs=[],
342
+ outputs=[softsubs_files, hardsubs_files]
343
+ )
344
+
345
+ stop_btn.click(
346
+ fn=stop_process,
347
+ inputs=[],
348
+ outputs=output
349
+ )
350
+
351
+ gr.Markdown("""
352
+ <center>WebUI Desenvolvida por Rafa.Godoy</center>
353
+ <center>Agradecimentos ao MatheusBach por desenvolver o LeGen</center>
354
+ """)
355
+
356
+ if __name__ == "__main__":
357
+ demo.launch()
ffmpeg_utils.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ import re
4
+ import subprocess
5
+ from pathlib import Path
6
+ import sys
7
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
8
+ from ffmpeg_progress_yield import FfmpegProgress
9
+ from tqdm import tqdm
10
+
11
+ import file_utils
12
+
13
+
14
+ def insert_subtitle(input_media_path: Path, subtitles_path: [Path], burn_subtitles: bool, output_video_path: Path, codec_video: str = "h264", codec_audio: str = "aac"):
15
+ # use only valid srt files
16
+ subtitles_path: [Path] = file_utils.validate_files(subtitles_path)
17
+
18
+ # insert in comand the basics of ffmpeg
19
+ cmd_ffmpeg = ["ffmpeg", "-y"]
20
+ cmd_ffmpeg_input_map = []
21
+
22
+ # add ffmpeg input main media
23
+ cmd_ffmpeg.extend(["-i", "file:" + input_media_path.as_posix()])
24
+ # map video stream, audio, subtitle, data and metadata
25
+ map_index = cmd_ffmpeg.count("-i") - 1
26
+ cmd_ffmpeg_input_map.extend(["-map", f"{map_index}:V?", "-map", f"{map_index}:a",
27
+ "-ignore_unknown"])
28
+
29
+ # detect if input has video channels
30
+ result: str = subprocess.run(["ffprobe", "-i", "file:" + input_media_path.as_posix(), "-show_streams",
31
+ "-select_streams", "V", "-loglevel", "error"], capture_output=True, text=True).stdout
32
+ no_video = True if result is None or "DISPOSITION:attached_pic=0" not in result else False
33
+
34
+ # if input has no video channels, map a 1280x720 black screen
35
+ if no_video:
36
+ # create a background image if media is only audio
37
+ background_tempfile: file_utils.TempFile = file_utils.TempFile(
38
+ "", ".jpeg")
39
+
40
+ # create a 1280x720 jpeg image
41
+ with open(file=background_tempfile.getpath(), mode="wb") as file:
42
+ file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EABQRAQAAAAAAAAAAAAAAAAAAALD/2gAIAQMBAT8QYQ//xAAUEQEAAAAAAAAAAAAAAAAAAACw/9oACAECAQE/EGEP/8QAJxABAAIBAwQBBQADAAAAAAAAAQARMRAhYUFRcZFgIDBwgbGQodD/2gAIAQEAAT8Q/wAAQxcRGn8ALwJTuzsMx9u1Z+srWRSh9kCWMQ7fs1LupVu7+peBKd2PYxKaflgsHeBRRBVBcAWTBCg2wHVlMgTO8W4jveZjiccrL9IFjegWFy8tnHKyzERUQLmCmusz6BY3mCCrhAqw0Be8Gt92ccv8QqyxPBEVssO1cqWYl/iccpedoNavfT+8wedHe0C5iU22lt6BRRNzY2hVvsygTMzHYnHNm/SFQxHRZxzOMfJcOgRDALKiC1Jj8SxQRWLMRShqJlaG/GF9A8TaLjxo5gq9FsQVemR61oK/aog26xbX0mfTL5mDzMEdFgBYy5dhKdlfaGCOlaGZ/ExxaVGsZgaf3mDzofeJhSBClubE0Q3CAFkzwKKijZXQUotJ7EW1zP8AJjHMQcgzBLVGCY/Ew+JkMMQFOIF0vzKNhvEIqIbGZg1fmCJZAFgLuALIs3ArSEKPWIJSQDYbTPoskQFJCjY6TFcMof7ncXEUHWGCOn+cz+IZu/UQcl6YGn99Sq36g5SkxEdgIY5iy0gAbbEtUYIXIRRcRWk3Rl8TJmb5NicsVk6UdX3FXLehgMW66CwYtllHV96CmGopyrBTDU5Yq5b0CwxS2rFOV15Za7tirluCwZyzM5HuW3d7zke4KYanI9y0tbiq3P2zaItw7aCMKTke5yPegXWOQ68sU5dLrE5Yq5bgphqcj3BTCkU5X3+ChRsgupFOCpn/AKTt/9k="))
43
+
44
+ # get input media duration
45
+ duration_sec = subprocess.run(["ffprobe", "-i", "file:" + input_media_path.as_posix(), "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"],
46
+ capture_output=True, text=True).stdout.split("\n")[0].split('.')[0]
47
+
48
+ cmd_ffmpeg.extend(["-t", f"{duration_sec}", "-loop", "1",
49
+ "-framerate", "10", "-i", background_tempfile.getpath().as_posix()])
50
+ map_index = cmd_ffmpeg.count("-i") - 1
51
+ # unmap #0, remap #0 with no video, map #1 (generated video from image)
52
+ cmd_ffmpeg_input_map.extend(
53
+ ["-map", "-0", "-map", f"0:a", "-map", f"0:d?", "-map", f"0:t?", "-map", f"{map_index}:V", "-ignore_unknown"])
54
+
55
+ # map each subtitle
56
+ for i, subtitle in enumerate(subtitles_path):
57
+ cmd_ffmpeg.extend(["-i", "file:" + subtitle.as_posix()])
58
+ map_index = cmd_ffmpeg.count("-i") - 1
59
+ cmd_ffmpeg_input_map.extend(["-map", f"{map_index}:s"])
60
+
61
+ # add comand to burn subtitles if its demanded and has at least one valid subtitle in the array. Burn the first one. Also ensure hwupload if necessary
62
+ vf_hwupload = True if codec_video.endswith(
63
+ ("_nvenc", "_amf", "_v4l2m2m", "_qsv", "_vaapi", "_videotoolbox", "_cuvid")) else False
64
+ hw_device = codec_video.split("_")[-1] if vf_hwupload else None
65
+ # set hw_device as cuda if api is nvenc or cuvid
66
+ if hw_device == "nvenc" or hw_device == "cuvid":
67
+ hw_device = "cuda"
68
+ vf_hwupload = False
69
+
70
+ # set hw_device as vaapi if api is v4l2m2m or amf
71
+ if hw_device == "v4l2m2m" or hw_device == "amf":
72
+ hw_device = "vaapi"
73
+
74
+ if burn_subtitles and len(subtitles_path) > 0:
75
+ # create temp file for .srt
76
+ srt_temp = file_utils.TempFile(
77
+ "", file_ext=".srt")
78
+
79
+ file_utils.copy_file_if_different(
80
+ subtitles_path[0], srt_temp.getpath(), True)
81
+
82
+ # align subtitles to botton center if hass video and to center center if only audio with black screen
83
+ sub_align = 10 if no_video else 2
84
+
85
+ # insert scale, subtitles filter and hwupload if required
86
+ # scale at minimul height of 480p. it also will make the dimensions divisible by 2
87
+ cmd_ffmpeg.extend(
88
+ ["-vf", f"format=nv12, scale='ceil((max(480,ih)*iw/ih)/2)*2:ceil(max(480,ih)/2)*2', subtitles=\'{add_ffmpeg_escape_chars(srt_temp.temp_file.name)}\':force_style='Alignment={sub_align},Fontname=Jost,PrimaryColour=&H03fcff,Fontsize=18,BackColour=&H80000000,Bold=1,Spacing=0.09,Outline=1,Shadow=0,MarginL=10,MarginR=10'" + (', hwupload' if vf_hwupload else '')])
89
+ else:
90
+ if vf_hwupload:
91
+ cmd_ffmpeg.extend(["-vf", f"format=nv12, hwupload"])
92
+ burn_subtitles = False
93
+
94
+ cmd_ffmpeg.extend(cmd_ffmpeg_input_map)
95
+
96
+ # init a hw_device if hwupload is set on video filters
97
+ if hw_device is not None:
98
+ cmd_ffmpeg.extend(["-init_hw_device", hw_device])
99
+
100
+ # add the remaining parameters and output path
101
+ cmd_ffmpeg.extend(["-c:V", codec_video, "-c:a", codec_audio, "-c:s", "mov_text",
102
+ "-pix_fmt", "yuv420p", "-movflags", "+faststart",
103
+ "-sws_flags", "bicubic+accurate_rnd+full_chroma_int+full_chroma_inp",
104
+ "file:" + output_video_path.as_posix()])
105
+
106
+ # run FFmpeg command with a fancy progress bar
107
+ ff = FfmpegProgress(cmd_ffmpeg)
108
+ with tqdm(total=100, position=0, ascii="░▒█", desc="Inserting subtitles" if not burn_subtitles else "Burning subtitles", unit="%", unit_scale=True, leave=True, bar_format="{desc} [{bar}] {percentage:3.0f}% | {rate_fmt}{postfix} | ETA: {remaining} | ⏱: {elapsed}") as pbar:
109
+ for progress in ff.run_command_with_progress():
110
+ pbar.update(progress - pbar.n)
111
+
112
+ # destroy unecessary file
113
+ if 'srt_temp' in locals():
114
+ srt_temp.destroy()
115
+
116
+
117
+ def extract_audio_wav(input_media_path: Path, output_path: Path):
118
+ # set the FFMpeg command
119
+ cmd_ffmpeg = ["ffmpeg", "-y", "-i", "file:" + input_media_path.as_posix(),
120
+ "-vn", "-c:a", "pcm_s16le", "-ac", "1", "-ar", "16000", "file:" + output_path.as_posix()]
121
+
122
+ # run FFmpeg command with a fancy progress bar
123
+ ff = FfmpegProgress(cmd_ffmpeg)
124
+ with tqdm(total=100, position=0, ascii="░▒█", desc="Extracting audio", unit="%", unit_scale=True, leave=True, bar_format="{desc} {percentage:3.0f}% | ETA: {remaining} | ⏱: {elapsed}") as pbar:
125
+ for progress in ff.run_command_with_progress():
126
+ pbar.update(progress - pbar.n)
127
+
128
+
129
+ def extract_short_wav(input_media_path: Path, output_path: Path):
130
+ # get input media duration
131
+ duration_sec = subprocess.run(["ffprobe", "-i", "file:" + input_media_path.as_posix(), "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"],
132
+ capture_output=True, text=True).stdout.split("\n")[0].replace("\n", "").replace(" ", "").replace(" ", "").replace("00:", "").replace(":", "").split(".")[0]
133
+
134
+ if int(duration_sec) > 240:
135
+ start_sec = int(duration_sec) - 120
136
+ end_sec = int(duration_sec) - 60
137
+ elif int(duration_sec) > 120:
138
+ start_sec = int(duration_sec) - 80
139
+ end_sec = int(duration_sec) - 20
140
+ elif int(duration_sec) > 80:
141
+ start_sec = int(duration_sec) - 60
142
+ end_sec = int(duration_sec) - 20
143
+ else:
144
+ start_sec = 0
145
+ end_sec = int(duration_sec)
146
+
147
+ # set the FFMpeg command
148
+ cmd_ffmpeg = ["ffmpeg", "-y", "-ss", f"{start_sec}", "-t", f"{end_sec}", "-i", "file:" + input_media_path.as_posix(),
149
+ "-vn", "-c:a", "pcm_s16le", "-af", "loudnorm", "-ac", "1", "-ar", "16000", "file:" + output_path.as_posix()]
150
+
151
+ # run FFmpeg command with a fancy progress bar
152
+ ff = FfmpegProgress(cmd_ffmpeg)
153
+ with tqdm(total=100, position=0, ascii="░▒█", desc="Extracting audio", unit="%", unit_scale=True, leave=False, bar_format="{desc} {percentage:3.0f}% | ETA: {remaining} | ⏱: {elapsed}") as pbar:
154
+ for progress in ff.run_command_with_progress():
155
+ pbar.update(progress - pbar.n)
156
+
157
+
158
+ def add_ffmpeg_escape_chars(string):
159
+ new_string = ""
160
+ for char in string:
161
+ if os.name == 'nt':
162
+ if char == ":" or char == "\x5c":
163
+ new_string += "\x5c"
164
+ new_string += char
165
+ return new_string
file_utils.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import filecmp
2
+ import os
3
+ import shutil
4
+ import tempfile
5
+ from inspect import currentframe, getframeinfo
6
+ from pathlib import Path
7
+
8
+ # return the itens in array that is not inexisting or empty
9
+ def validate_files(paths):
10
+ valid_files = [path for path in paths if file_is_valid(path)]
11
+ return valid_files
12
+
13
+ # check if a file is existing and not empty
14
+ def file_is_valid(path):
15
+ if path is not None and path.is_file():
16
+ size = path.stat().st_size
17
+ if size > 0:
18
+ return True
19
+ return False
20
+
21
+ # validate if an string is a valid dir or path with valid content
22
+ def check_valid_path(path_str):
23
+ # create a Path object from the input string
24
+ path = Path(path_str)
25
+
26
+ # check if the path exists
27
+ if not path.exists():
28
+ raise FileNotFoundError(f"The path '{path_str}' does not exist.")
29
+
30
+ # check if it's a directory with at least one file or a valid file with content
31
+ if path.is_dir():
32
+ # check if the directory has at least one file with content
33
+ files_with_content = [file for file in path.iterdir() if file.is_file() and file.stat().st_size > 0]
34
+ if not files_with_content:
35
+ raise ValueError(f"The directory '{path_str}' does not contain any files with content.")
36
+ elif path.is_file():
37
+ # check if the file has content
38
+ if path.stat().st_size == 0:
39
+ raise ValueError(f"The file '{path_str}' does not contain any content.")
40
+ else:
41
+ raise ValueError(f"The path '{path_str}' is neither a valid directory nor a valid file.")
42
+
43
+ return path
44
+
45
+ # validate if an string is a valid dir or path with valid content
46
+ def check_existing_path(path_str):
47
+ # create a Path object from the input string
48
+ path = Path(path_str)
49
+
50
+ # check if the path exists
51
+ if not path.exists():
52
+ raise FileNotFoundError(f"The path '{path_str}' does not exist.")
53
+
54
+ # check if it's a directory with at least one file or a valid file with content
55
+ if not path.is_dir() and not path.is_file():
56
+ raise ValueError(f"The path '{path_str}' is neither a valid directory nor a valid file.")
57
+
58
+ return path_str
59
+
60
+ # create a tempfile class to use as object
61
+ class TempFile:
62
+
63
+ def __init__(self, final_path: Path, file_ext: str = None):
64
+ self.final_path: Path = None if final_path is None else Path(
65
+ final_path)
66
+ self.file_ext = file_ext
67
+ os.makedirs(Path(Path(getframeinfo(
68
+ currentframe()).filename).resolve().parent, "temp"), exist_ok=True)
69
+ self.temp_file: tempfile.NamedTemporaryFile = tempfile.NamedTemporaryFile(dir=Path(Path(getframeinfo(currentframe()).filename).resolve().parent, "temp"),
70
+ delete=False, suffix=file_ext)
71
+
72
+ self.temp_file_name = self.temp_file.name
73
+ self.temp_file_path: Path = Path(self.temp_file.name)
74
+
75
+ self.temp_file.close()
76
+
77
+ # return the actual path of the file
78
+ def getpath(self):
79
+ if self.temp_file_path.is_file():
80
+ return self.temp_file_path
81
+ elif file_is_valid(self.final_path):
82
+ return self.final_path
83
+ else:
84
+ return None
85
+
86
+ # return the actual path of the file if not empty
87
+ def getvalidpath(self):
88
+ if file_is_valid(self.temp_file_path):
89
+ return self.temp_file_path
90
+ elif file_is_valid(self.final_path):
91
+ return self.final_path
92
+ else:
93
+ return None
94
+
95
+ # save the temp file into final path
96
+ def save(self, overwrite_if_valid: bool = True, update_path: Path = None):
97
+ # update final path case user specifies it
98
+ if update_path is None:
99
+ path: Path = self.final_path
100
+ else:
101
+ path: Path = update_path
102
+
103
+ try:
104
+ # if file not valid ou overwrite is enabled, move overwiting existing file
105
+ if not file_is_valid(self.final_path) or overwrite_if_valid:
106
+ os.makedirs(path.parent, exist_ok=True)
107
+ shutil.move(self.temp_file_path, path)
108
+ self.final_path = path
109
+ except Exception as e:
110
+ print(f"Error saving file: {e}")
111
+ return
112
+
113
+ # delete the file
114
+ def destroy(self):
115
+ try:
116
+ # destroy temporary file if it exists
117
+ if file_is_valid(self.temp_file_path):
118
+ os.remove(self.temp_file_path)
119
+ except Exception:
120
+ return
121
+
122
+ # copy an source file to destination if destination file is not equals to source
123
+ def copy_file_if_different(src_file: Path, dst_file: Path, silent: bool = False):
124
+ if file_is_valid(dst_file):
125
+ # Check if destination file exists and is different from source file
126
+ if filecmp.cmp(src_file, dst_file) and not silent:
127
+ print(f"{dst_file} already exists and is the same. No need to copy.")
128
+ return
129
+
130
+ os.makedirs(dst_file.parent, exist_ok=True)
131
+ shutil.copyfile(src_file, dst_file)
132
+ if not silent:
133
+ print(f"copied to {dst_file}")
134
+
135
+ # function to delete dir and all its content using shutil
136
+ def delete_folder(path: Path):
137
+ if path.is_dir():
138
+ shutil.rmtree(path)
139
+
140
+
141
+ def update_folder_times(folder_path):
142
+ folder_path = Path(folder_path)
143
+
144
+ # Keep track of the newest file's modification time for this folder
145
+ newest_file_time = None
146
+
147
+ for item in folder_path.iterdir():
148
+ # Check if the item is a file
149
+ if item.is_file():
150
+ file_time = item.stat().st_mtime # Get modification time of the file
151
+
152
+ # Update the newest_file_time if it's the first file or if the current file is newer
153
+ if newest_file_time is None or file_time > newest_file_time:
154
+ newest_file_time = file_time
155
+
156
+ # If the item is a subfolder, recursively update its times and find its newest file time
157
+ elif item.is_dir():
158
+ subfolder_newest_time = update_folder_times(item)
159
+
160
+ # Update the newest_file_time if a subfolder's newest file is newer
161
+ if newest_file_time is None or (subfolder_newest_time is not None and subfolder_newest_time > newest_file_time):
162
+ newest_file_time = subfolder_newest_time
163
+
164
+ # Update the folder's modification and creation times with the newest_file_time
165
+ if newest_file_time is not None:
166
+ # Convert to an integer (necessary on some systems)
167
+ newest_file_time = int(newest_file_time)
168
+ os.utime(path=folder_path, times=(newest_file_time, newest_file_time))
169
+
170
+ return newest_file_time # Return the newest_file_time to update the parent folder's time
header.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ badges = """
2
+ <div style="display: flex; justify-content: center;">
3
+
4
+ <span style="margin-right: 5px">
5
+
6
+ [ ![GitHub](https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white) ](https://github.com/matheusbach/legen)
7
+
8
+ </span>
9
+
10
+ </div>
11
+ """
12
+
13
+ description = """
14
+ # <center>LeGen</center>
15
+ <center>Conheça a comunidade no <a href='https://t.me/+Q_Czz4LbbrA0Y2Ux' target='_blank'>Telegram</a></center>
16
+ """
i18n/__pycache__/i18n.cpython-39.pyc ADDED
Binary file (2.41 kB). View file
 
i18n/config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "theme": {
3
+ "file": "legen.py",
4
+ "class": "LeGen"
5
+ },
6
+ "plugins": [],
7
+ "discord_presence": false,
8
+ "lang": {
9
+ "override": false,
10
+ "selected_lang": "pt_BR"
11
+ },
12
+ "flask_server": false,
13
+ "version": ""
14
+ }
i18n/i18n.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ import json
3
+ from pathlib import Path
4
+ from locale import getdefaultlocale
5
+
6
+ now_dir = os.getcwd()
7
+ sys.path.append(now_dir)
8
+
9
+
10
+ class I18nAuto:
11
+ LANGUAGE_PATH = os.path.join(now_dir, "i18n", "languages")
12
+
13
+ def __init__(self, language=None):
14
+ with open(os.path.join(now_dir, "i18n", "config.json"), "r") as f:
15
+ config = json.load(f)
16
+ override = config["lang"]["override"]
17
+ lang_prefix = config["lang"]["selected_lang"]
18
+
19
+ self.language = lang_prefix
20
+
21
+ if override == False:
22
+ language = language or getdefaultlocale()[0]
23
+ lang_prefix = language[:2] if language is not None else "en"
24
+ available_languages = self._get_available_languages()
25
+ matching_languages = [
26
+ lang for lang in available_languages if lang.startswith(lang_prefix)
27
+ ]
28
+ self.language = matching_languages[0] if matching_languages else "en_US"
29
+
30
+ self.language_map = self._load_language_list()
31
+
32
+ def _load_language_list(self):
33
+ try:
34
+ file_path = Path(self.LANGUAGE_PATH) / f"{self.language}.json"
35
+ with open(file_path, "r", encoding="utf-8") as f:
36
+ return json.load(f)
37
+ except FileNotFoundError:
38
+ raise FileNotFoundError(
39
+ f"Failed to load language file for {self.language}. Check if the correct .json file exists."
40
+ )
41
+
42
+ def _get_available_languages(self):
43
+ language_files = [path.stem for path in Path(self.LANGUAGE_PATH).glob("*.json")]
44
+ return language_files
45
+
46
+ def _language_exists(self, language):
47
+ return (Path(self.LANGUAGE_PATH) / f"{language}.json").exists()
48
+
49
+ def __call__(self, key):
50
+ return self.language_map.get(key, key)
i18n/languages/en_US.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Selected folder: ": "Selected folder: ",
3
+ "No folder selected": "No folder selected",
4
+ "Select Folder": "Select Folder",
5
+ "Transcription Engine": "Transcription Engine",
6
+ "Model": "Model",
7
+ "Compute Type": "Compute Type",
8
+ "Device": "Device",
9
+ "Batch Size": "Batch Size",
10
+ "Input Language": "Input Language",
11
+ "Translate to": "Translate to",
12
+ "Video Codec": "Video Codec",
13
+ "Audio Codec": "Audio Codec",
14
+ "Normalize folder times": "Normalize folder times",
15
+ "Overwrite existing files": "Overwrite existing files",
16
+ "Copy non-video files": "Copy non-video files",
17
+ "Disable SRT generation": "Disable SRT generation",
18
+ "Disable softsubs": "Disable softsubs",
19
+ "Disable hardsubs": "Disable hardsubs",
20
+ "Softsubs Output Path": "Softsubs Output Path",
21
+ "Hardsubs Output Path": "Hardsubs Output Path",
22
+ "Browse": "Browse",
23
+ "Run LeGen": "Run LeGen",
24
+ "Processing stopped by user": "Processing stopped by user",
25
+ "Please select a folder": "Please select a folder",
26
+ "Selected folder path does not exist": "Selected folder path does not exist",
27
+ "legen.py not found in current directory": "legen.py not found in current directory",
28
+ "Stop LeGen": "Stop LeGen",
29
+ "Processing...": "Processing...",
30
+ "Transcription Settings": "Transcription Settings",
31
+ "Output Settings": "Output Settings",
32
+ "Options": "Options",
33
+
34
+ "gradio": "gradio",
35
+
36
+ "Input Path": "Input Path",
37
+ "Enter path to file or folder": "Enter path to file or folder",
38
+ "Stop": "Stop"
39
+
40
+ }
i18n/languages/pt_BR.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Selected folder:": "Pasta selecionada:",
3
+ "No folder selected": "Nenhuma pasta selecionada",
4
+ "Select Folder": "Selecionar Pasta",
5
+ "Transcription Engine": "Motor de Transcrição",
6
+ "Model": "Modelo",
7
+ "Compute Type": "Tipo de Computação",
8
+ "Device": "Dispositivo",
9
+ "Batch Size": "Tamanho do Lote",
10
+ "Input Language": "Idioma de Entrada",
11
+ "Translate to": "Traduzir para",
12
+ "Video Codec": "Codec de Vídeo",
13
+ "Audio Codec": "Codec de Áudio",
14
+ "Normalize folder times": "Normalizar tempos da pasta",
15
+ "Overwrite existing files": "Sobrescrever arquivos existentes",
16
+ "Copy non-video files": "Copiar arquivos não de vídeo",
17
+ "Disable SRT generation": "Desabilitar geração de SRT",
18
+ "Disable softsubs": "Desabilitar softsubs",
19
+ "Disable hardsubs": "Desabilitar hardsubs",
20
+ "Softsubs Output Path": "Caminho de Saída das Softsubs",
21
+ "Hardsubs Output Path": "Caminho de Saída das Hardsubs",
22
+ "Browse": "Navegar",
23
+ "Run LeGen": "Executar LeGen",
24
+ "Processing stopped by user": "Processamento interrompido pelo usuário",
25
+ "Please select a folder": "Por favor, selecione uma pasta",
26
+ "Selected folder path does not exist": "Caminho da pasta selecionada não existe",
27
+ "legen.py not found in current directory": "legen.py não encontrado no diretório atual",
28
+ "Stop LeGen": "Parar LeGen",
29
+ "Processing...": "Processando...",
30
+ "Transcription Settings": "Configurações de Transcrição",
31
+ "Output Settings": "Configurações de Saída",
32
+ "Options": "Opções",
33
+
34
+ "gradio": "gradio",
35
+
36
+ "Input Path": "Caminho de entrada",
37
+ "Enter path to file or folder": "Digite o caminho para o arquivo ou pasta",
38
+ "Stop": "Parar"
39
+ }
i18n/scan.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import json
3
+ from pathlib import Path
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
+ def process_file(file_path):
26
+ with open(file_path, "r") as f:
27
+ code = f.read()
28
+ if "I18nAuto" in code:
29
+ tree = ast.parse(code)
30
+ i18n_strings = extract_i18n_strings(tree)
31
+ print(file_path, len(i18n_strings))
32
+ return i18n_strings
33
+ return []
34
+
35
+
36
+ # Use pathlib for file handling
37
+ py_files = Path(".").rglob("*.py")
38
+
39
+ # Use a set to store unique strings
40
+ code_keys = set()
41
+
42
+ for py_file in py_files:
43
+ strings = process_file(py_file)
44
+ code_keys.update(strings)
45
+
46
+ print()
47
+ print("Total unique:", len(code_keys))
48
+
49
+ standard_file = "languages/en_US.json"
50
+ with open(standard_file, "r", encoding="utf-8") as f:
51
+ standard_data = json.load(f, object_pairs_hook=OrderedDict)
52
+ standard_keys = set(standard_data.keys())
53
+
54
+ # Combine unused and missing keys sections
55
+ unused_keys = standard_keys - code_keys
56
+ missing_keys = code_keys - standard_keys
57
+
58
+ print("Unused keys:", len(unused_keys))
59
+ for unused_key in unused_keys:
60
+ print("\t", unused_key)
61
+
62
+ print("Missing keys:", len(missing_keys))
63
+ for missing_key in missing_keys:
64
+ print("\t", missing_key)
65
+
66
+ code_keys_dict = OrderedDict((s, s) for s in code_keys)
67
+
68
+ # Use context manager for writing back to the file
69
+ with open(standard_file, "w", encoding="utf-8") as f:
70
+ json.dump(code_keys_dict, f, ensure_ascii=False, indent=4, sort_keys=True)
71
+ f.write("\n")
legen.ipynb ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "id": "G7E7eZwJ7F5c"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "#@title *Prepare* { display-mode: \"form\", run: \"auto\" }\n",
12
+ "\n",
13
+ "#@markdown # **Prepare the environment**\n",
14
+ "#@markdown Execute to install necessary packages, modules, fonts\n",
15
+ "\n",
16
+ "#@markdown Mount Google Drive at /content/drive (your drive folder at /content/drive/MyDrive):\n",
17
+ "mount_gdrive = True #@param {type:\"boolean\"}\n",
18
+ "#@markdown Force mount again. Useful for bug cases:\n",
19
+ "force_remount = False #@param {type:\"boolean\"}\n",
20
+ "\n",
21
+ "# remove the old log\n",
22
+ "!rm -rf error_log.txt > /dev/null\n",
23
+ "\n",
24
+ "import os\n",
25
+ "import subprocess\n",
26
+ "from google.colab import drive\n",
27
+ "\n",
28
+ "# mount Google Drive\n",
29
+ "if mount_gdrive:\n",
30
+ " print(\"Mounting your Google Drive | Waiting user Allow Access | \", end='')\n",
31
+ " try:\n",
32
+ " drive.mount('/content/drive/', force_remount=force_remount)\n",
33
+ " except Exception as e:\n",
34
+ " print(f\"[✗]: {e}\")\n",
35
+ "\n",
36
+ "# update code\n",
37
+ "print(\"Ensuring the LeGen code is existing and updated...\", end='')\n",
38
+ "repo_url = \"https://github.com/matheusbach/legen.git\"\n",
39
+ "local_folder = \"/content/src\" # LeGen source path\n",
40
+ "\n",
41
+ "# Create directory if it does not exist\n",
42
+ "os.makedirs(local_folder, exist_ok=True)\n",
43
+ "\n",
44
+ "# Try git status in the directory\n",
45
+ "git_task = \"git fetch\"\n",
46
+ "process = subprocess.Popen(git_task, cwd=local_folder, shell=True)\n",
47
+ "return_code = process.wait()\n",
48
+ "if return_code == 0:\n",
49
+ " git_task = \"git fetch && git reset --hard origin/main && git pull\"\n",
50
+ "else:\n",
51
+ " !rm -rf local_folder > /dev/null\n",
52
+ " os.makedirs(local_folder, exist_ok=True)\n",
53
+ " git_task = f\"git clone {repo_url} {local_folder}\"\n",
54
+ "\n",
55
+ "# If it is a git repo, fetch, reset, and pull. Else, clone.\n",
56
+ "with open('/content/error_log.txt', 'a') as f:\n",
57
+ " process = subprocess.Popen(git_task, cwd=local_folder, shell=True, stderr=f)\n",
58
+ " return_code = process.wait()\n",
59
+ " print(\"[✔]\" if return_code == 0 else \"[✗]\")\n",
60
+ "\n",
61
+ "# install pip requirements.txt updating\n",
62
+ "print(\"Installing or updating pip requirements...\", end='')\n",
63
+ "with open('/content/error_log.txt', 'a') as f:\n",
64
+ " process = subprocess.Popen('pip3 install --upgrade $(grep -v \"git+https://github.com/matheusbach/whisperx.git\" requirements.txt | grep -v \"torch\") && pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 && pip3 install git+https://github.com/matheusbach/whisperx.git --upgrade', cwd=local_folder, shell=True, stderr=f)\n",
65
+ " return_code = process.wait()\n",
66
+ " print(\"[✔]\" if return_code == 0 else \"[✗]\")\n",
67
+ "\n",
68
+ "# install ffmpeg and xvfb\n",
69
+ "print(\"Installing FFmpeg and xvfb...\", end='')\n",
70
+ "with open('/content/error_log.txt', 'a') as f:\n",
71
+ " process = subprocess.Popen('apt update -y ; apt install ffmpeg xvfb -y', shell=True, stderr=f)\n",
72
+ " return_code = process.wait()\n",
73
+ " print(\"[✔]\" if return_code == 0 else \"[✗]\")\n",
74
+ "\n",
75
+ "# install pip requirements.txt updating\n",
76
+ "print(\"Installing fonts...\", end='')\n",
77
+ "with open('/content/error_log.txt', 'a') as f:\n",
78
+ " process = subprocess.Popen('echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections && apt install -y ttf-mscorefonts-installer && fc-cache -f -v', shell=True, stderr=f)\n",
79
+ " return_code = process.wait()\n",
80
+ " print(\"[✔]\" if return_code == 0 else \"[✗]\")\n",
81
+ "\n",
82
+ "# create a virtual display\n",
83
+ "os.system('Xvfb :1 -screen 0 2560x1440x8 &') # create virtual display with size 1600x1200 and 8 bit color. Color can be changed to 24, 16 or 8\n",
84
+ "os.environ['DISPLAY'] = ':1.0' # tell X clients to use our virtual DISPLAY :1.0.\n",
85
+ "\n",
86
+ "print(\"\\nPreparation tasks done.\")"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": null,
92
+ "metadata": {
93
+ "id": "Bz77fHta9JxG"
94
+ },
95
+ "outputs": [],
96
+ "source": [
97
+ "#@title *Configure* { display-mode: \"form\", run: \"auto\" }\n",
98
+ "#@markdown # **Define Software Settings**\n",
99
+ "#@markdown ---\n",
100
+ "#@markdown ## General Options\n",
101
+ "#@markdown Set where your files are located (your Drive is the base /content/drive/MyDrive):\n",
102
+ "import os\n",
103
+ "from IPython.display import display\n",
104
+ "import ipywidgets as widgets\n",
105
+ "input_path = \"/content/drive/MyDrive/LeGen/media\" #@param {type:\"string\"}\n",
106
+ "#@markdown Set where output soft subs (.srt and embed) videos will be saved on your Drive:\n",
107
+ "output_softsubs_path = \"/content/drive/MyDrive/LeGen/softsubs\" #@param {type:\"string\"}\n",
108
+ "#@markdown Set where output hard subs (burned in) videos will be saved on your Drive:\n",
109
+ "output_hardsubs_path = \"/content/drive/MyDrive/LeGen/hardsubs\" #@param {type:\"string\"}\n",
110
+ "\n",
111
+ "#@markdown ---\n",
112
+ "overwrite = False #@param {type:\"boolean\"}\n",
113
+ "normalize = False #@param {type:\"boolean\"}\n",
114
+ "copy_extra_files = True #@param {type:\"boolean\"}\n",
115
+ "\n",
116
+ "# generate_srt_files = True #@param {type:\"boolean\"}\n",
117
+ "generate_softsub = True #@param {type:\"boolean\"}\n",
118
+ "generate_hardsub = True # @param {type:\"boolean\"}\n",
119
+ "\n",
120
+ "# buttons for directory create\n",
121
+ "button = widgets.Button(description=\"Create directories!\")\n",
122
+ "output = widgets.Output()\n",
123
+ "\n",
124
+ "\n",
125
+ "def on_button_clicked(b):\n",
126
+ " # Create input and output directories if it does not exist\n",
127
+ " os.makedirs(input_path, exist_ok=True)\n",
128
+ " if generate_softsub:\n",
129
+ " os.makedirs(output_softsubs_path, exist_ok=True)\n",
130
+ " if generate_hardsub:\n",
131
+ " os.makedirs(output_hardsubs_path, exist_ok=True)\n",
132
+ " with output:\n",
133
+ " print(\"Done.\")\n",
134
+ "\n",
135
+ "\n",
136
+ "button.on_click(on_button_clicked)\n",
137
+ "display(button, output)\n",
138
+ "\n",
139
+ "#@markdown ---\n",
140
+ "#@markdown ## Transcription Settings:\n",
141
+ "transcription_engine = 'WhisperX' # @param [\"Whisper\", \"WhisperX\"]\n",
142
+ "transcription_device = 'auto' #@param [\"auto\", \"cpu\", \"cuda\"]\n",
143
+ "transcription_model = 'large' #@param [\"tiny\", \"small\", \"medium\", \"large\", \"large-v1\", \"large-v2\", \"large-v3\"]\n",
144
+ "compute_type = 'default' # @param [\"default\", \"int8\", \"int16\", \"float16\", \"float32\"]\n",
145
+ "batch_size = 12 # @param {type: \"number\"}\n",
146
+ "transcription_input_lang = 'auto detect' #@param [\"auto detect\", \"af\", \"am\", \"ar\", \"as\", \"az\", \"ba\", \"be\", \"bg\", \"bn\", \"bo\", \"br\", \"bs\", \"ca\", \"cs\", \"cy\", \"da\", \"de\", \"el\", \"en\", \"es\", \"et\", \"eu\", \"fa\", \"fi\", \"fo\", \"fr\", \"gl\", \"gu\", \"ha\", \"haw\", \"he\", \"hi\", \"hr\", \"ht\", \"hu\", \"hy\", \"id\", \"is\", \"it\", \"ja\", \"jw\", \"ka\", \"kk\", \"km\", \"kn\", \"ko\", \"la\", \"lb\", \"ln\", \"lo\", \"lt\", \"lv\", \"mg\", \"mi\", \"mk\", \"ml\", \"mn\", \"mr\", \"ms\", \"mt\", \"my\", \"ne\", \"nl\", \"nn\", \"no\", \"oc\", \"pa\", \"pl\", \"ps\", \"pt\", \"ro\", \"ru\", \"sa\", \"sd\", \"si\", \"sk\", \"sl\", \"sn\", \"so\", \"sq\", \"sr\", \"su\", \"sv\", \"sw\", \"ta\", \"te\", \"tg\", \"th\", \"tk\", \"tl\", \"tr\", \"tt\", \"uk\", \"ur\", \"uz\", \"vi\", \"yi\", \"yo\", \"zh\"]\n",
147
+ "\n",
148
+ "#@markdown ---\n",
149
+ "#@markdown ## Translation Settings:\n",
150
+ "#@markdown Set the destination langrage code. Set to same as original to skip translation\n",
151
+ "target_language_code = 'pt' #@param [\"af\", \"sq\", \"am\", \"ar\", \"hy\", \"as\", \"ay\", \"az\", \"bm\", \"eu\", \"be\", \"bn\", \"bho\", \"bs\", \"bg\", \"ca\", \"ceb\", \"zh-CN\", \"zh-TW\", \"co\", \"hr\", \"cs\", \"da\", \"dv\", \"doi\", \"nl\", \"en\", \"eo\", \"et\", \"ee\", \"fil\", \"fi\", \"fr\", \"fy\", \"gl\", \"ka\", \"de\", \"el\", \"gn\", \"gu\", \"ht\", \"ha\", \"haw\", \"he\", \"hi\", \"hmn\", \"hu\", \"is\", \"ig\", \"ilo\", \"id\", \"ga\", \"it\", \"ja\", \"jv\", \"kn\", \"kk\", \"km\", \"rw\", \"gom\", \"ko\", \"kri\", \"ku\", \"ckb\", \"ky\", \"lo\", \"la\", \"lv\", \"ln\", \"lt\", \"lg\", \"lb\", \"mk\", \"mai\", \"mg\", \"ms\", \"ml\", \"mt\", \"mi\", \"mr\", \"mni-Mtei\", \"lus\", \"mn\", \"my\", \"ne\", \"no\", \"ny\", \"or\", \"om\", \"ps\", \"fa\", \"pl\", \"pt\", \"pa\", \"qu\", \"ro\", \"ru\", \"sm\", \"sa\", \"gd\", \"nso\", \"sr\", \"st\", \"sn\", \"sd\", \"si\", \"sk\", \"sl\", \"so\", \"es\", \"su\", \"sw\", \"sv\", \"tl\", \"tg\", \"ta\", \"tt\", \"te\", \"th\", \"ti\", \"ts\", \"tr\", \"tk\", \"ak\", \"uk\", \"ur\", \"ug\", \"uz\", \"vi\", \"cy\", \"xh\", \"yi\", \"yo\", \"zu\"]\n",
152
+ "\n",
153
+ "#@markdown ---\n",
154
+ "#@markdown ## Video Settings:\n",
155
+ "codec_video = \"h264\" #@param [\"h264\", \"hevc\", \"mpeg4\"]\n",
156
+ "video_hardware_api = \"auto\" #@param [\"auto\", \"none\", \"nvenc\", \"vaapi\", \"amf\", \"v4l2m2m\", \"qsv\", \"videotoolbox\", \"cuvid\"]\n",
157
+ "\n",
158
+ "codec_audio = \"aac\" #@param [\"aac\", \"libopus\", \"libmp3lame\", \"pcm_s16le\"]"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": null,
164
+ "metadata": {
165
+ "id": "n4KSJ9BL7JOs"
166
+ },
167
+ "outputs": [],
168
+ "source": [
169
+ "#@title *Run* { display-mode: \"form\" }\n",
170
+ "#@markdown # **Run LeGen.py**\n",
171
+ "\n",
172
+ "print(\"Starting LeGen...\")\n",
173
+ "import torch\n",
174
+ "try:\n",
175
+ " import tensorflow # required in Colab to avoid protobuf compatibility issues\n",
176
+ "except ImportError:\n",
177
+ " pass\n",
178
+ "\n",
179
+ "# Create input and output directories if it does not exist\n",
180
+ "os.makedirs(input_path, exist_ok=True)\n",
181
+ "if generate_softsub:\n",
182
+ " os.makedirs(output_softsubs_path, exist_ok=True)\n",
183
+ "if generate_hardsub:\n",
184
+ " os.makedirs(output_hardsubs_path, exist_ok=True)\n",
185
+ "\n",
186
+ "#build query\n",
187
+ "query = f\" -i '{input_path}'\"\n",
188
+ "query += f\" --output_softsubs '{output_softsubs_path}'\"\n",
189
+ "query += f\" --output_hardsubs '{output_hardsubs_path}'\"\n",
190
+ "query += \" --overwrite\" if overwrite else \"\"\n",
191
+ "query += \" --norm\" if normalize else \"\"\n",
192
+ "query += \" --copy_files\" if not copy_extra_files else \"\"\n",
193
+ "query += \" --disable_softsubs\" if not generate_softsub else \"\"\n",
194
+ "query += \" --disable_hardsubs\" if not generate_hardsub else \"\"\n",
195
+ "query += f\" -ts:e {transcription_engine.lower()}\"\n",
196
+ "query += f\" -ts:d {transcription_device.lower()}\"\n",
197
+ "query += f\" -ts:m {transcription_model}\"\n",
198
+ "query += f\" -ts:c {compute_type}\"\n",
199
+ "query += f\" -ts:b {batch_size}\"\n",
200
+ "query += f\" --input_lang {transcription_input_lang}\" if transcription_input_lang != \"auto detect\" else \"\"\n",
201
+ "query += f\" --translate {target_language_code.lower()}\"\n",
202
+ "query += f\" -c:v {codec_video}\" + (\"\" if video_hardware_api == \"none\" else f\"_{video_hardware_api}\" if video_hardware_api != \"auto\" else \"_nvenc\" if torch.cuda.is_available() else \"\")\n",
203
+ "query += f\" -c:a {codec_audio}\"\n",
204
+ "\n",
205
+ "#run python script\n",
206
+ "print(f\"command line: python3 /content/src/legen.py {query}\", end=\"\\n\\n\")\n",
207
+ "!python3 /content/src/legen.py $query"
208
+ ]
209
+ }
210
+ ],
211
+ "metadata": {
212
+ "accelerator": "GPU",
213
+ "colab": {
214
+ "gpuType": "T4",
215
+ "provenance": []
216
+ },
217
+ "kernelspec": {
218
+ "display_name": "Python 3",
219
+ "name": "python3"
220
+ },
221
+ "language_info": {
222
+ "name": "python"
223
+ }
224
+ },
225
+ "nbformat": 4,
226
+ "nbformat_minor": 0
227
+ }
legen.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import subprocess
4
+ import time
5
+ from inspect import currentframe, getframeinfo
6
+ from pathlib import Path
7
+
8
+ import ffmpeg_utils
9
+ import file_utils
10
+ import translate_utils
11
+ from utils import time_task, audio_extensions, video_extensions, check_other_extensions
12
+
13
+ version = "v0.16"
14
+
15
+ # Terminal colors
16
+ default = "\033[1;0m"
17
+ gray = "\033[1;37m"
18
+ wblue = "\033[1;36m"
19
+ blue = "\033[1;34m"
20
+ yellow = "\033[1;33m"
21
+ green = "\033[1;32m"
22
+ red = "\033[1;31m"
23
+
24
+ print(f"""
25
+ {blue}888 {gray} .d8888b.
26
+ {blue}888 {gray}d88P Y88b
27
+ {blue}888 {gray}888 888
28
+ {blue}888 .d88b. {gray}888 .d88b. 88888b.
29
+ {blue}888 d8P Y8b {gray}888 88888 d8P Y8b 888 "88b
30
+ {blue}888 88888888 {gray}888 888 88888888 888 888
31
+ {blue}888 Y8b. {gray}Y88b d88P Y8b. 888 888
32
+ {blue}88888888 "Y8888 {gray} "Y8888P88 "Y8888 888 888
33
+
34
+ legen {version} - github.com/matheusbach/legen{default}
35
+ python {__import__('sys').version}
36
+ """)
37
+ time.sleep(1.5)
38
+
39
+ # Define parameters and configurations
40
+ parser = argparse.ArgumentParser(prog="LeGen", description="Uses AI to locally transcribes speech from media files, generating subtitle files, translates the generated subtitles, inserts them into the mp4 container, and burns them directly into video",
41
+ argument_default=True, allow_abbrev=True, add_help=True, usage='LeGen -i INPUT_PATH [other options]')
42
+ parser.add_argument("-i", "--input_path",
43
+ help="Path to media files. Can be a folder containing files or an individual file", required=True, type=Path)
44
+ parser.add_argument("--norm", default=False, action="store_true",
45
+ help="Normalize folder times and run vidqa on input_path before starting processing files")
46
+ parser.add_argument("-ts:e", "--transcription_engine", type=str, default="whisperx",
47
+ help="Transcription engine. Possible values: whisperx (default), whisper")
48
+ parser.add_argument("-ts:m", "--transcription_model", type=str, default="medium",
49
+ help="Path or name of the Whisper transcription model. A larger model will consume more resources and be slower, but with better transcription quality. Possible values: tiny, base, small, medium (default), large, ...")
50
+ parser.add_argument("-ts:d", "--transcription_device", type=str, default="auto",
51
+ help="Device to run the transcription through Whisper. Possible values: auto (default), cpu, cuda")
52
+ parser.add_argument("-ts:c", "--transcription_compute_type", type=str, default="auto",
53
+ help="Quantization for the neural network. Possible values: auto (default), int8, int8_float32, int8_float16, int8_bfloat16, int16, float16, bfloat16, float32")
54
+ parser.add_argument("-ts:b", "--transcription_batch", type=int, default=4,
55
+ help="Number of simultaneous segments being transcribed. Higher values will speed up processing. If you have low RAM/VRAM, long duration media files or have buggy subtitles, reduce this value to avoid issues. Only works using transcription_engine whisperx. (default: 4)")
56
+ parser.add_argument("--translate", type=str, default="none",
57
+ help="Translate subtitles to language code if not the same as origin. (default: don't translate)")
58
+ parser.add_argument("--input_lang", type=str, default="auto",
59
+ help="Indicates (forces) the language of the voice in the input media (default: auto)")
60
+ parser.add_argument("-c:v", "--codec_video", type=str, default="h264", metavar="VIDEO_CODEC",
61
+ help="Target video codec. Can be used to set acceleration via GPU or another video API [codec_api], if supported (ffmpeg -encoders). Ex: h264, libx264, h264_vaapi, h264_nvenc, hevc, libx265 hevc_vaapi, hevc_nvenc, hevc_cuvid, hevc_qsv, hevc_amf (default: h264)")
62
+ parser.add_argument("-c:a", "--codec_audio", type=str, default="aac", metavar="AUDIO_CODEC",
63
+ help="Target audio codec. (default: aac). Ex: aac, libopus, mp3, vorbis")
64
+ parser.add_argument("-o:s", "--output_softsubs", default=None, type=Path,
65
+ help="Path to the folder or output file for the video files with embedded softsub (embedded in the mp4 container and .srt files). (default: softsubs_ + input_path)")
66
+ parser.add_argument("-o:h", "--output_hardsubs", default=None, type=Path,
67
+ help="Output folder path for video files with burned-in captions and embedded in the mp4 container. (default: hardsubs_ + input_path)")
68
+ parser.add_argument("--overwrite", default=False, action="store_true",
69
+ help="Overwrite existing files in output directories")
70
+ parser.add_argument("--disable_srt", default=False, action="store_true",
71
+ help="Disable .srt file generation and don't insert subtitles in mp4 container of output_softsubs")
72
+ parser.add_argument("--disable_softsubs", default=False, action="store_true",
73
+ help="Don't insert subtitles in mp4 container of output_softsubs. This option continues generating .srt files")
74
+ parser.add_argument("--disable_hardsubs", default=False, action="store_true",
75
+ help="Disable subtitle burn in output_hardsubs")
76
+ parser.add_argument("--copy_files", default=False, action="store_true",
77
+ help="Copy other (non-video) files present in input directory to output directories. Only generate the subtitles and videos")
78
+ args = parser.parse_args()
79
+
80
+ if not args.output_softsubs and not args.input_path.is_file():
81
+ args.output_softsubs = compatibility_path if (compatibility_path := Path(args.input_path.parent, "legen_srt_" + args.input_path.name)).exists() else Path(args.input_path.parent, "softsubs_" + args.input_path.name)
82
+ if not args.output_hardsubs and not args.input_path.is_file():
83
+ args.output_hardsubs = compatibility_path if (compatibility_path := Path(args.input_path.parent, "legen_burned_" + args.input_path.name)).exists() else Path(args.input_path.parent, "hardsubs_" + args.input_path.name)
84
+
85
+ if args.transcription_device == "auto":
86
+ import torch
87
+ torch_device = ("cuda" if torch.cuda.is_available() else "cpu")
88
+ else:
89
+ torch_device = str.lower(args.transcription_device)
90
+
91
+ transcription_compute_type = args.transcription_compute_type if args.transcription_compute_type != "default" else "float16" if not torch_device == "cpu" else "float32"
92
+
93
+ args.transcription_model = "large-v3" if args.transcription_model == "large" else args.transcription_model
94
+
95
+ # ----------------------------------------------------------------------------
96
+
97
+ if args.norm:
98
+ # normalize video using vidqa
99
+ with time_task(message_start=f"Running {wblue}vidqa{default} and updating folder modifiation times in {gray}{args.input_path}{default}", end="\n"):
100
+ subprocess.run(["vidqa", "-i", args.input_path, "-m", "unique", "-fd",
101
+ Path(Path(getframeinfo(currentframe()).filename).resolve().parent, "vidqa_data")])
102
+ # update folder time structure
103
+ file_utils.update_folder_times(args.input_path)
104
+
105
+ # load whisper model
106
+ with time_task(message_start=f"\nLoading {args.transcription_engine} model: {wblue}{args.transcription_model}{default} ({transcription_compute_type}) on {wblue}{torch_device}{default}", end="\n"):
107
+ if args.transcription_engine == 'whisperx':
108
+ import whisperx
109
+ import whisperx_utils
110
+
111
+ whisper_model = whisperx.load_model(
112
+ whisper_arch=args.transcription_model, device=torch_device, compute_type=transcription_compute_type, asr_options={"repetition_penalty": 1, "prompt_reset_on_temperature": 0.5, "no_repeat_ngram_size": 2,})
113
+ elif args.transcription_engine == 'whisper':
114
+ import whisper
115
+
116
+ import whisper_utils
117
+ whisper_model = whisper.load_model(
118
+ name=args.transcription_model, device=torch_device, in_memory=True)
119
+ else:
120
+ raise ValueError(f'Unsupported transcription engine {args.transcription_engine}. Supported values: whisperx, whisper')
121
+
122
+ with time_task(message="⌛ Processing files for"):
123
+ path: Path
124
+ for path in (item for item in sorted(sorted(Path(args.input_path).rglob('*'), key=lambda x: x.stat().st_mtime), key=lambda x: len(x.parts)) if item.is_file()):
125
+ rel_path = path.relative_to(args.input_path)
126
+ with time_task(message_start=f"\nProcessing {yellow}{rel_path.as_posix()}{default}", end="\n", message="⌚ Done in"):
127
+ try:
128
+ # define file type by extensions
129
+ if path.suffix.lower() in video_extensions:
130
+ file_type = "video"
131
+ elif path.suffix.lower() in audio_extensions:
132
+ file_type = "audio"
133
+ else:
134
+ file_type = "other"
135
+
136
+ if file_type == "video" or file_type == "audio":
137
+ # define paths
138
+ origin_media_path = path
139
+ dupe_filename = len(check_other_extensions(path, list(video_extensions | audio_extensions))) > 1
140
+ posfix_extension = path.suffix.lower().replace('.', '_') if dupe_filename else ''
141
+
142
+ softsub_video_dir = Path(args.output_softsubs, rel_path.parent)
143
+ burned_video_dir = Path(args.output_hardsubs, rel_path.parent)
144
+ # output video extension will be changed to .mp4
145
+ softsub_video_path = Path(args.output_softsubs, rel_path.stem + posfix_extension + ".mp4")
146
+ hardsub_video_path = Path(burned_video_dir, rel_path.stem + posfix_extension + ".mp4")
147
+ subtitle_translated_path = Path(
148
+ softsub_video_dir, rel_path.stem + posfix_extension + f"_{args.translate}.srt")
149
+ subtitles_path = []
150
+
151
+ if args.input_lang == "auto":
152
+ # extract audio
153
+ audio_short_extracted = file_utils.TempFile(
154
+ None, file_ext=".wav")
155
+ ffmpeg_utils.extract_short_wav(
156
+ origin_media_path, audio_short_extracted.getpath())
157
+ # detect language
158
+ print("Detecting audio language: ", end='', flush=True)
159
+ if args.transcription_engine == 'whisperx':
160
+ audio_language = whisperx_utils.detect_language(
161
+ whisper_model, audio_short_extracted.getpath())
162
+ if args.transcription_engine == 'whisper':
163
+ audio_language = whisper_utils.detect_language(
164
+ whisper_model, audio_short_extracted.getpath())
165
+ print(f"{gray}{audio_language}{default}")
166
+
167
+ audio_short_extracted.destroy()
168
+ else:
169
+ audio_language = args.input_lang
170
+ print(f"Forced input audio language: {gray}{audio_language}{default}")
171
+ # set path after get transcribed language
172
+ subtitle_transcribed_path = Path(
173
+ softsub_video_dir, rel_path.stem + posfix_extension + f"_{audio_language}.srt")
174
+ # create temp file for .srt
175
+ transcribed_srt_temp = file_utils.TempFile(
176
+ subtitle_transcribed_path, file_ext=".srt")
177
+ # skip transcription if transcribed srt for this language is existing (without overwrite neabled) or will not be used in LeGen process
178
+ if (file_utils.file_is_valid(subtitle_transcribed_path)) or ((args.disable_hardsubs or file_utils.file_is_valid(hardsub_video_path)) and (args.disable_srt or file_utils.file_is_valid(subtitle_transcribed_path))) and not args.overwrite:
179
+ print("Transcription is unnecessary. Skipping.")
180
+ else:
181
+ # extract audio
182
+ audio_extracted = file_utils.TempFile(None, file_ext=".wav")
183
+ ffmpeg_utils.extract_audio_wav(
184
+ origin_media_path, audio_extracted.getpath())
185
+ # transcribe saving subtitles to temp .srt file
186
+ if args.transcription_engine == 'whisperx':
187
+ print(f"{wblue}Transcribing{default} with {gray}WhisperX{default}")
188
+ whisperx_utils.transcribe_audio(
189
+ whisper_model, audio_extracted.getpath(), transcribed_srt_temp.getpath(), audio_language, device=torch_device, batch_size=args.transcription_batch)
190
+ if args.transcription_engine == 'whisper':
191
+ print(f"{wblue}Transcribing{default} with {gray}Whisper{default}")
192
+ whisper_utils.transcribe_audio(
193
+ model=whisper_model, audio_path=audio_extracted.getpath(), srt_path=transcribed_srt_temp.getpath(), lang=audio_language, disable_fp16=False if transcription_compute_type == "float16" or transcription_compute_type == "fp16" else True)
194
+
195
+ audio_extracted.destroy()
196
+ # if save .srt is enabled, save it to destination dir, also update path with language code
197
+ if not args.disable_srt:
198
+ transcribed_srt_temp.save()
199
+ subtitles_path.append(transcribed_srt_temp.getvalidpath())
200
+ # translate transcribed subtitle using Google Translate if transcribed language is not equals to target
201
+ # skip translation if translation has not requested, has equal source and output language, if file is existing (without overwrite neabled) or will not be used in LeGen process
202
+ if args.translate == "none":
203
+ pass # translation not requested
204
+ elif args.translate == audio_language:
205
+ print("Translation is unnecessary because input and output language are the same. Skipping.")
206
+ elif (args.disable_hardsubs or file_utils.file_is_valid(hardsub_video_path)) and (args.disable_srt or (file_utils.file_is_valid(subtitle_translated_path) and file_utils.file_is_valid(subtitle_transcribed_path) and file_utils.file_is_valid(subtitle_translated_path))) and not args.overwrite:
207
+ print("Translation is unnecessary. Skipping.")
208
+ subtitles_path.insert(0, subtitle_translated_path)
209
+ elif file_utils.file_is_valid(subtitle_translated_path):
210
+ print("Translated file found. Skipping translation.")
211
+ subtitles_path.insert(0, subtitle_translated_path)
212
+ elif transcribed_srt_temp.getvalidpath():
213
+ # create the temp .srt translated file
214
+ translated_srt_temp = file_utils.TempFile(
215
+ subtitle_translated_path, file_ext=".srt")
216
+
217
+ # translating with google translate public API
218
+ print(f"{wblue}Translating{default} with {gray}Google Translate{default}")
219
+ subs = translate_utils.translate_srt_file(
220
+ transcribed_srt_temp.getvalidpath(), translated_srt_temp.getpath(), args.translate)
221
+ if not args.disable_srt:
222
+ translated_srt_temp.save()
223
+
224
+ subtitles_path.insert(0, translated_srt_temp.getvalidpath())
225
+ if not args.disable_softsubs:
226
+ if file_utils.file_is_valid(softsub_video_path) and not args.overwrite:
227
+ print(f"Existing video file {gray}{softsub_video_path}{default}. Skipping subtitle insert")
228
+ else:
229
+ # create the temp .mp4 with srt in video container
230
+ video_softsubs_temp = file_utils.TempFile(
231
+ softsub_video_path, file_ext=".mp4")
232
+
233
+ # insert subtitle into container using ffmpeg
234
+ print(f"{wblue}Inserting subtitle{default} in mp4 container using {gray}FFmpeg{default}")
235
+ ffmpeg_utils.insert_subtitle(input_media_path=origin_media_path, subtitles_path=subtitles_path,
236
+ burn_subtitles=False, output_video_path=video_softsubs_temp.getpath(),
237
+ codec_video=args.codec_video, codec_audio=args.codec_audio)
238
+ video_softsubs_temp.save()
239
+ if not args.disable_hardsubs:
240
+ if file_utils.file_is_valid(hardsub_video_path) and not args.overwrite:
241
+ print(f"Existing video file {gray}{hardsub_video_path}{default}. Skipping subtitle burn")
242
+ else:
243
+ # create the temp .mp4 with srt in video container
244
+ video_hardsubs_temp = file_utils.TempFile(
245
+ hardsub_video_path, file_ext=".mp4")
246
+ # insert subtitle into container and burn using ffmpeg
247
+ print(f"{wblue}Inserting subtitle{default} in mp4 container and {wblue}burning{default} using {gray}FFmpeg{default}")
248
+ ffmpeg_utils.insert_subtitle(input_media_path=origin_media_path, subtitles_path=subtitles_path,
249
+ burn_subtitles=True, output_video_path=video_hardsubs_temp.getpath(),
250
+ codec_video=args.codec_video, codec_audio=args.codec_audio)
251
+ video_hardsubs_temp.save()
252
+ else:
253
+ print("not a video file")
254
+ if args.copy_files:
255
+ if not args.disable_srt:
256
+ # copia o arquivo extra para pasta que contém também os arquivos srt
257
+ file_utils.copy_file_if_different(path, Path(
258
+ args.output_softsubs, rel_path))
259
+ if not args.disable_hardsubs:
260
+ # copia o arquivo extra para pasta que contém os videos queimados
261
+ file_utils.copy_file_if_different(path, Path(
262
+ args.output_hardsubs, rel_path))
263
+ except Exception as e:
264
+ file = path.as_posix()
265
+ print(f"{red}ERROR !!!{default} {file}")
266
+ print(f"{yellow}check legen-errors.txt for details{default}")
267
+ # extract the relevant information from the exception object
268
+ current_time = time.strftime("%y/%m/%d %H:%M:%S", time.localtime())
269
+
270
+ error_message = f"[{current_time}] {file}: {type(e).__name__}: {str(e)}"
271
+ # write the error message to a file
272
+ with open(Path(Path(getframeinfo(currentframe()).filename).resolve().parent, "legen-errors.txt"), "a") as f:
273
+ f.write(error_message + "\n")
274
+ f.close()
275
+
276
+ print("Deleting temp folder")
277
+ file_utils.delete_folder(
278
+ Path(Path(getframeinfo(currentframe()).filename).resolve().parent, "temp"))
279
+
280
+ print(f"{green}Tasks done!{default}")
pyproject.toml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools", "setuptools_scm[toml]>=6.2"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "LeGen"
7
+ authors = [
8
+ {name = "Matheus Bach"},
9
+ ]
10
+ description = "LeGen is a Python script that normalizes video files using vidqa, transcribes subtitles from audio with Whisper, translates generated subtitles using Google Translator, saves subtitles in .srt files, inserts subtitles into .mp4 container and burns subtitles directly onto videos using FFmpeg "
11
+ readme = "README.md"
12
+ requires-python = ">=3.7"
13
+ keywords = ["subtitle", "whisper", "ffmpeg", "translator", "video"]
14
+ license = {text = "GPL 3"}
15
+ classifiers = [
16
+ "Framework :: LeGen",
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+ dependencies = [
20
+ "deep_translator",
21
+ "ffmpeg_progress_yield",
22
+ "openai_whisper",
23
+ "pysrt",
24
+ "torch",
25
+ "tqdm",
26
+ "whisper",
27
+ "vidqa",
28
+ "whisperx"
29
+ ]
30
+ py_modules = [
31
+ "translate_utils",
32
+ "file_utils",
33
+ "whisper_utils",
34
+ "whisperx_utils",
35
+ "ffmpeg_utils"
36
+ ]
37
+ dynamic = ["version"]
38
+
39
+
40
+ [project.scripts]
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ deep_translator
2
+ ffmpeg_progress_yield
3
+ openai_whisper
4
+ pysrt
5
+ torch
6
+ tqdm
7
+ whisper
8
+ vidqa
9
+ git+https://github.com/matheusbach/whisperx.git
10
+ flet
11
+ tensorflow
subtitle_utils.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import tkinter as tk
4
+ from pathlib import Path
5
+
6
+ import pysrt
7
+
8
+
9
+ def SaveSegmentsToSrt(segments: list, output_path: Path):
10
+ # Create the subtitle file
11
+ subs = pysrt.SubRipFile()
12
+ sub_idx = 1
13
+
14
+ for i in range(len(segments)):
15
+ start_time = segments[i]["start"]
16
+ end_time = segments[i]["end"]
17
+ duration = end_time - start_time
18
+ timestamp = f"{start_time:.3f} - {end_time:.3f}"
19
+ text = segments[i]["text"]
20
+
21
+ sub = pysrt.SubRipItem(index=sub_idx, start=pysrt.SubRipTime(seconds=start_time),
22
+ end=pysrt.SubRipTime(seconds=end_time), text=text)
23
+ subs.append(sub)
24
+ sub_idx += 1
25
+
26
+ # make dir and save .srt
27
+ os.makedirs(output_path.parent, exist_ok=True)
28
+ subs.save(output_path)
29
+
30
+
31
+ def string_width(text, font_name="Jost", font_size=18):
32
+ """
33
+ Determines the width of a string using tkinter.
34
+ """
35
+ tries_remaining = 5
36
+
37
+ while (tries_remaining > 0):
38
+ tries_remaining -= 1
39
+ try:
40
+ root = tk.Tk()
41
+ width = tk.font.Font(name=font_name, size=font_size,
42
+ weight="bold").measure(text)
43
+ root.destroy()
44
+ return width
45
+ except Exception:
46
+ pass
47
+
48
+ # all failed, return 60% of height per char
49
+ return len(text) * font_size * 0.60
50
+
51
+
52
+ def is_punctuation_end(word):
53
+ """Verifica se a palavra termina com uma pontuação."""
54
+ return any(word.endswith(punct) for punct in ['.', ',', '!', '?', ':', ';'])
55
+
56
+
57
+ def split_segments(segments, max_width_px=1440, font_name="Jost", font_size=18):
58
+ """
59
+ Split segments based on the max width provided.
60
+ """
61
+ new_segments = []
62
+ for segment in segments:
63
+ words = segment['words']
64
+ current_words = []
65
+ current_width = 0
66
+
67
+ for word in words:
68
+ # Calculate the width with a space after the word
69
+ added_width = string_width(
70
+ word['word'] + " ", font_name, font_size)
71
+ isolated_sentence_ending = is_punctuation_end(word['word']) and not (
72
+ current_words and is_punctuation_end(current_words[-1]['word']))
73
+ possible_logical_break_point = len(current_words) >= 2 and len(
74
+ current_words[-1]['word']) <= 3 and not len(current_words[-2]['word']) <= 3
75
+
76
+ if (current_width + added_width < max_width_px) or len(current_words) == 0 or isolated_sentence_ending or possible_logical_break_point:
77
+ current_words.append(word)
78
+ current_width += added_width
79
+ else:
80
+ new_segments.append({
81
+ 'text': ' '.join(word['word'] for word in current_words),
82
+ 'start': next((word['start'] for word in current_words if 'start' in word), segment['start']),
83
+ 'end': next((word['end'] for word in reversed(current_words) if 'end' in word), segment['end']),
84
+ 'words': current_words.copy()
85
+ })
86
+ current_words = [word]
87
+ current_width = added_width
88
+
89
+ # For any remaining words
90
+ if current_words:
91
+ new_segments.append({
92
+ 'text': ' '.join(word['word'] for word in current_words),
93
+ 'start': next((word['start'] for word in current_words if 'start' in word), segment['start']),
94
+ 'end': next((word['end'] for word in reversed(current_words) if 'end' in word), segment['end']),
95
+ 'words': current_words
96
+ })
97
+
98
+ return new_segments
99
+
100
+
101
+ def split_string_to_max_lines(text, max_width=720, max_lines=2, font_name="Jost", font_size=18):
102
+ threshold = max_width * 0.8
103
+ total_text_width = string_width(text, font_name, font_size)
104
+
105
+ if total_text_width <= threshold or max_lines < 2:
106
+ return [text]
107
+
108
+ words = text.split()
109
+ lines = []
110
+ current_line_words = []
111
+ current_line_width = 0
112
+
113
+ for i, word in enumerate(words):
114
+ word_width = string_width(word + ' ', font_name, font_size)
115
+ isolated_sentence_ending = is_punctuation_end(word) and not (
116
+ current_line_words and is_punctuation_end(current_line_words[-1]))
117
+ possible_logical_break_point = len(current_line_words) >= 2 and len(
118
+ current_line_words[-1]) <= 3 and not len(current_line_words[-2]) <= 3
119
+
120
+ if current_line_width + word_width < total_text_width / max_lines or len(current_line_words) == 0 or isolated_sentence_ending or possible_logical_break_point:
121
+ current_line_words.append(word)
122
+ current_line_width += word_width
123
+ else:
124
+ lines.append(' '.join(current_line_words))
125
+ current_line_words = [word]
126
+ current_line_width = word_width
127
+
128
+ if len(lines) == max_lines - 1:
129
+ remaining_words = words[i:]
130
+ lines.append(' '.join(remaining_words))
131
+ break
132
+
133
+ if current_line_words and len(lines) < max_lines:
134
+ lines.append(' '.join(current_line_words))
135
+
136
+ return lines
137
+
138
+
139
+ def adjust_times(segments, extra_end_time=1.0):
140
+ for i in range(len(segments) - 1): # We don't need to check the last segment
141
+ current_end = segments[i]['end']
142
+ next_start = segments[i + 1]['start']
143
+
144
+ gap = next_start - current_end
145
+
146
+ # If the gap is more than 1.5 + extra_end_time
147
+ if gap > 1.5 + extra_end_time:
148
+ segments[i]['end'] = current_end + extra_end_time
149
+
150
+ # If the gap is less than 1.5 + extra_end_time
151
+ elif gap < 1.5 + extra_end_time:
152
+ segments[i]['end'] = next_start
153
+
154
+ return segments
155
+
156
+
157
+ def format_segments(segments: list, max_line_width_px: int = 380, max_lines_per_segment: int = 2):
158
+ print('Formatting segments...', end='', flush=True)
159
+
160
+ segments = split_segments(
161
+ segments, max_line_width_px * max_lines_per_segment)
162
+
163
+ for segment in segments:
164
+ segment["text"] = "\n".join(split_string_to_max_lines(
165
+ text=segment["text"], max_width=max_line_width_px, max_lines=max_lines_per_segment))
166
+
167
+ segments = adjust_times(segments)
168
+
169
+ print('\r ', end='\r', flush=True)
170
+
171
+ return segments
translate_utils.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ from pathlib import Path
4
+
5
+ import deep_translator
6
+ import pysrt
7
+ import tqdm.asyncio
8
+ import subtitle_utils
9
+ from utils import format_time
10
+
11
+ # all entence endings for japanese and normal people languages
12
+ sentence_endings = ['.', '!', '?', ')', 'よ', 'ね',
13
+ 'の', 'さ', 'ぞ', 'な', 'か', '!', '。', '」', '…']
14
+
15
+ # a good separator is a char or string that doenst change the translation quality but is near ever preserved in result at same or near position
16
+ separator = " ◌ "
17
+ separator_unjoin = separator.replace(' ', '')
18
+ chunk_max_chars = 4999
19
+
20
+
21
+ def translate_srt_file(srt_file_path: Path, translated_subtitle_path: Path, target_lang):
22
+ # Load the original SRT file
23
+ subs = pysrt.open(srt_file_path, encoding='utf-8')
24
+
25
+ # Extract the subtitle content and store it in a list. Also rejoin all lines splited
26
+ sub_content = [' '.join(sub.text.strip().splitlines()) for sub in subs]
27
+
28
+ # Make chunks of at maximum $chunk_max_chars to stay under Google Translate public API limits
29
+ chunks = join_sentences(sub_content, chunk_max_chars) or []
30
+
31
+ # Empty list to store enumerated translated chunks
32
+ translated_chunks = [None] * len(chunks)
33
+
34
+ tasks = []
35
+ # Limit to 7 concomitant running tasks
36
+ semaphore = asyncio.Semaphore(7)
37
+
38
+ # Async chunks translate function
39
+ async def translate_async():
40
+ async def run_translate(index, chunk, lang):
41
+ while True:
42
+ try:
43
+ async with semaphore:
44
+ result = await asyncio.wait_for(translate_chunk(index, chunk, lang), 120)
45
+ translated_chunks[index] = result
46
+ break
47
+ except Exception:
48
+ # Restart task
49
+ await asyncio.sleep(3)
50
+
51
+ for index, chunk in enumerate(chunks):
52
+ task = asyncio.create_task(
53
+ run_translate(index, chunk, target_lang))
54
+ tasks.append(task)
55
+
56
+ for tsk in tqdm.asyncio.tqdm_asyncio.as_completed(tasks, total=len(tasks), desc="Translating", unit="chunks", unit_scale=False, leave=True, bar_format="{desc} {percentage:3.0f}% | {n_fmt}/{total_fmt} | ETA: {remaining} | ⏱: {elapsed}"):
57
+ await tsk
58
+
59
+ # Cria um loop de eventos e executa as tasks
60
+ loop = asyncio.get_event_loop()
61
+ loop.run_until_complete(translate_async())
62
+
63
+ print('Processing translation...', end='')
64
+
65
+ # Unjoin lines within each chunk that end with a sentence ending
66
+ unjoined_texts = [unjoin_sentences(
67
+ chunk, translated_chunks[i], separator_unjoin) or "" for i, chunk in enumerate(chunks)]
68
+ unjoined_texts = [text for sublist in unjoined_texts for text in sublist]
69
+
70
+ # Split lines as necessary targeting same number of lines as original string
71
+ for i, segment in enumerate(unjoined_texts):
72
+ unjoined_texts[i] = "\n".join(subtitle_utils.split_string_to_max_lines(
73
+ text=segment, max_width=0, max_lines=len(subs[i].text.splitlines())))
74
+
75
+ # Combine the original and translated subtitle content
76
+ for i, sub in enumerate(subs):
77
+ sub.text = unjoined_texts[i]
78
+
79
+ # Save the translated SRT file
80
+ os.makedirs(translated_subtitle_path.parent, exist_ok=True)
81
+ subs.save(translated_subtitle_path, encoding='utf-8')
82
+
83
+ print('\r ', end='\r')
84
+
85
+ return subs
86
+
87
+ # Async chunk translate function
88
+
89
+
90
+ async def translate_chunk(index, chunk, target_lang):
91
+ while True:
92
+ try:
93
+ # Translate the subtitle content of the chunk using Google Translate
94
+ translator = deep_translator.google.GoogleTranslator(
95
+ source='auto', target=target_lang)
96
+ translated_chunk: str = await asyncio.wait_for(asyncio.get_event_loop().run_in_executor(None, translator.translate, chunk), 30)
97
+ await asyncio.sleep(0)
98
+
99
+ # if nothing is retuned, return the original chunk
100
+ if translated_chunk is None or len(translated_chunk.replace(separator.strip(), '').split()) == 0:
101
+ return chunk
102
+
103
+ return translated_chunk
104
+ except Exception as e:
105
+ # If an error occurred, retry
106
+ del translator
107
+ print(
108
+ f"\r[chunk {index}]: Exception: {e.__doc__} Retrying in 30 seconds...", flush=True)
109
+ await asyncio.sleep(30)
110
+
111
+
112
+ def join_sentences(lines, max_chars):
113
+ """
114
+ Joins the given list of strings in a way that each part ends with a sentence ending.
115
+ Adds a separator to all lines in the chunk.
116
+ """
117
+ joined_lines = []
118
+ current_chunk = ""
119
+
120
+ for line in lines:
121
+ if not line or line is None:
122
+ line = 'ㅤ' # invisible char (not a simple space)
123
+
124
+ if len(current_chunk) + len(line) + len(separator) <= max_chars:
125
+ current_chunk += line + separator
126
+ if any(line.endswith(ending) for ending in sentence_endings):
127
+ joined_lines.append(current_chunk)
128
+ current_chunk = ""
129
+ else:
130
+ if current_chunk:
131
+ joined_lines.append(current_chunk)
132
+ current_chunk = ""
133
+ if len(current_chunk) + len(line) + len(separator) <= max_chars:
134
+ current_chunk += line + separator
135
+ else:
136
+ # if a single line exceed max_chars, use maximum posible number of words. Discart the remaining
137
+ end_index = line.rfind(
138
+ ' ', 0, max_chars - (1 + len(separator)))
139
+
140
+ if end_index == - (1 + len(separator)):
141
+ end_index = max_chars - (1 + len(separator))
142
+
143
+ joined_lines.append(
144
+ (line[:end_index] + '…' + separator)[:max_chars])
145
+
146
+ # append a chunk wich doenst have a formal end with sentence endings
147
+ if current_chunk:
148
+ joined_lines.append(current_chunk)
149
+
150
+ return joined_lines
151
+
152
+
153
+ def unjoin_sentences(original_sentence: str, modified_sentence: str, separator: str):
154
+ """
155
+ Splits the original and modified sentences into lines based on the separator.
156
+ Tries to match the number of lines between the original and modified sentences.
157
+ """
158
+
159
+ if original_sentence is None:
160
+ return ' '
161
+
162
+ # split by separator, remove double spaces and empty or only space strings from list
163
+ original_lines = original_sentence.split(separator)
164
+ original_lines = [s.strip().replace(' ', ' ').lstrip(" ,.:;)") if s.strip().replace(' ', ' ').lstrip(" ,.:;)") else s
165
+ for s in original_lines if s.strip()]
166
+ original_lines = [s for s in original_lines if s]
167
+ original_lines = [s for s in original_lines if s.strip()]
168
+
169
+ if modified_sentence is None:
170
+ return original_lines or ' '
171
+
172
+ # fix strange formatation returned by google translate, case occuring
173
+ modified_sentence.replace(f"{separator_unjoin} ", f"{separator_unjoin}").replace(f" {separator_unjoin}", f"{separator_unjoin}").replace(
174
+ f"{separator_unjoin}.", f".{separator_unjoin}").replace(f"{separator_unjoin},", f",{separator_unjoin}")
175
+
176
+ # split by separator, remove double spaces and empty or only space strings from list
177
+ modified_lines = modified_sentence.split(separator_unjoin)
178
+ modified_lines = [s.strip().replace(' ', ' ').lstrip(" ,.:;)") if s.strip().replace(' ', ' ').lstrip(" ,.:;)") else s
179
+ for s in modified_lines if s.strip()]
180
+ modified_lines = [s for s in modified_lines if s]
181
+ modified_lines = [s for s in modified_lines if s.strip()]
182
+
183
+ # if original lines is "silence" sign, doenst translate
184
+ if original_lines == "..." or original_lines == "…":
185
+ return original_lines
186
+
187
+ # all ok, return lines
188
+ if len(original_lines) == len(modified_lines):
189
+ return modified_lines
190
+
191
+ # zero words? return original sentence, removing separator
192
+ original_word_count = sum(len(line.strip().split())
193
+ for line in original_lines)
194
+ modified_word_count = len(' '.join(modified_lines).strip().split())
195
+ if original_word_count == 0 or modified_word_count == 0:
196
+ return original_sentence.replace(separator, ' ').replace(' ', ' ')
197
+
198
+ # calculate proportion of words between original and translated
199
+ modified_words_proportion = modified_word_count / original_word_count
200
+ # list all modified words
201
+ modified_words = ' '.join(modified_lines).replace(separator, "").replace(
202
+ separator_unjoin, "").replace(" ", " ").strip().split(' ')
203
+
204
+ new_modified_lines = []
205
+ current_index = 0
206
+
207
+ # reconstruct lines based on proportion of original and translated words
208
+ for i in range(len(original_lines)):
209
+ # Calculate the number of words for the current modified sentence
210
+ num_words = int(
211
+ round(len(original_lines[i].strip().split()) * modified_words_proportion))
212
+
213
+ # Extract words from modified list
214
+ generated_line = ' '.join(
215
+ modified_words[current_index:current_index+num_words])
216
+
217
+ # Update the current index
218
+ current_index += num_words
219
+
220
+ # append remaining if is the last loop
221
+ if i == len(original_lines) - 1:
222
+ ' '.join([generated_line, ' '.join(
223
+ modified_words[current_index:])])
224
+
225
+ # Add modified sentence to the new list
226
+ new_modified_lines.append(generated_line.replace(" ", " ").strip())
227
+
228
+ # case it continues being shorter
229
+ while len(new_modified_lines) < len(original_lines):
230
+ new_modified_lines.append(new_modified_lines[-1])
231
+
232
+ return new_modified_lines or original_lines or ' '
ui.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import flet as ft
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ from typing import Optional
6
+ import asyncio
7
+ import threading
8
+ import sys
9
+ import os
10
+ import sys
11
+ from i18n.i18n import I18nAuto
12
+ i18n = I18nAuto()
13
+
14
+ # Força o uso de UTF-8 para o Python
15
+ os.environ["PYTHONIOENCODING"] = "utf-8"
16
+
17
+ # Para garantir que a codificação esteja correta no terminal
18
+ if sys.platform == "win32":
19
+ # No Windows, podemos forçar a codificação UTF-8 no console
20
+ os.system('chcp 65001')
21
+
22
+ # Redefine a configuração de codificação da saída padrão
23
+ sys.stdout.reconfigure(encoding='utf-8')
24
+ sys.stderr.reconfigure(encoding='utf-8')
25
+
26
+ import re
27
+
28
+ def clean_ansi(text: str) -> str:
29
+ """Remove códigos ANSI e limpa o texto para exibição no Flet"""
30
+ ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
31
+ return ansi_escape.sub('', text)
32
+
33
+
34
+ def process_output(line: str) -> str:
35
+ """Processa uma linha de saída, limpando-a apenas para exibição no Flet"""
36
+ clean_line = clean_ansi(line.strip())
37
+
38
+ # Verifica por padrões de progresso
39
+ if "%" in clean_line:
40
+ try:
41
+ # Extrai o número do progresso
42
+ progress_match = re.search(r'(\d+\.?\d*)%', clean_line)
43
+ if progress_match:
44
+ progress_value = float(progress_match.group(1)) / 100
45
+ return clean_line, progress_value
46
+ except ValueError:
47
+ pass
48
+
49
+ return clean_line, None
50
+
51
+
52
+
53
+ class LeGenUI:
54
+ def __init__(self):
55
+ self.input_path: Optional[Path] = None
56
+ self.selected_file_text: Optional[ft.Text] = None
57
+ self.dark_mode = True
58
+ self.progress = None
59
+ self.progress_text = None
60
+ self.page = None
61
+ self.processing = False
62
+ self.current_process = None
63
+ self.run_button = None
64
+
65
+ def create_credits_dialog(self):
66
+ async def close_dialog(e):
67
+ self.credits_dialog.open = False
68
+ await self.page.update_async()
69
+
70
+ async def open_url(e, url):
71
+ await self.page.launch_url_async(url)
72
+
73
+ return ft.AlertDialog(
74
+ modal=True,
75
+ title=ft.Text("Créditos", size=20, weight=ft.FontWeight.BOLD),
76
+ content=ft.Column([
77
+ ft.Text("LeGen - Legendas Generator", weight=ft.FontWeight.BOLD),
78
+ ft.Text("Desenvolvido com ❤️ pela comunidade"),
79
+ ft.Text(""),
80
+ ft.Text("Desenvolvedores:", weight=ft.FontWeight.BOLD),
81
+ ft.Text("• Matheus bach"),
82
+ ft.Text("• UI por Rafa.Godoy"),
83
+ ft.Text("• Colaboradores do GitHub"),
84
+ ft.Text(""),
85
+ ft.Text("Links:", weight=ft.FontWeight.BOLD),
86
+ ft.TextButton(
87
+ "GitHub",
88
+ icon=ft.icons.CODE,
89
+ on_click=lambda e: self.page.launch_url("https://github.com/matheusbach/legen")
90
+ ),
91
+ ft.TextButton(
92
+ "Telegram",
93
+ icon=ft.icons.TELEGRAM,
94
+ on_click=lambda e: self.page.launch_url("https://t.me/+Q_Czz4LbbrA0Y2Ux")
95
+ ),
96
+ ft.Text(""),
97
+ ft.Text("Tecnologias:", weight=ft.FontWeight.BOLD),
98
+ ft.Text("• Python"),
99
+ ft.Text("• WhisperX/Whisper"),
100
+ ft.Text("• FFmpeg"),
101
+ ft.Text("• Flet UI Framework"),
102
+ ], tight=True),
103
+ actions=[
104
+ ft.TextButton("Fechar", on_click=close_dialog),
105
+ ],
106
+ actions_alignment=ft.MainAxisAlignment.END,
107
+ )
108
+
109
+ def main(self, page: ft.Page):
110
+ self.page = page
111
+ page.title = "LeGen UI"
112
+ page.padding = 20
113
+ page.theme_mode = ft.ThemeMode.DARK if self.dark_mode else ft.ThemeMode.LIGHT
114
+ page.window.min_width = 1280
115
+ page.window.min_height = 720
116
+ page.scroll = ft.ScrollMode.AUTO
117
+
118
+ def toggle_dark_mode(e):
119
+ self.dark_mode = not self.dark_mode
120
+ page.theme_mode = ft.ThemeMode.DARK if self.dark_mode else ft.ThemeMode.LIGHT
121
+ page.update()
122
+
123
+ async def show_credits(e):
124
+ self.credits_dialog = self.create_credits_dialog()
125
+ self.page.dialog = self.credits_dialog
126
+ self.credits_dialog.open = True
127
+ await self.page.update_async()
128
+
129
+ async def pick_folder_result(e: ft.FilePickerResultEvent):
130
+ if e.path:
131
+ self.input_path = Path(e.path)
132
+ self.selected_file_text.value = f"{i18n('Selected folder:')} {self.input_path}"
133
+ await page.update_async()
134
+
135
+ async def pick_output_softsubs_result(e: ft.FilePickerResultEvent):
136
+ if e.path:
137
+ output_softsubs_path.value = e.path
138
+ await page.update_async()
139
+
140
+ async def pick_output_hardsubs_result(e: ft.FilePickerResultEvent):
141
+ if e.path:
142
+ output_hardsubs_path.value = e.path
143
+ await page.update_async()
144
+
145
+ #file_picker = ft.FilePicker(on_result=pick_file_result)
146
+ folder_picker = ft.FilePicker(on_result=pick_folder_result)
147
+ softsubs_folder_picker = ft.FilePicker(on_result=pick_output_softsubs_result)
148
+ hardsubs_folder_picker = ft.FilePicker(on_result=pick_output_hardsubs_result)
149
+
150
+ page.overlay.extend([folder_picker, softsubs_folder_picker, hardsubs_folder_picker])
151
+
152
+ self.selected_file_text = ft.Text(i18n("No folder selected"))
153
+
154
+ input_section = ft.Container(
155
+ content=ft.Column([
156
+ ft.Row([
157
+ ft.ElevatedButton(i18n("Select Folder"), on_click=lambda _: folder_picker.get_directory_path()),
158
+ ]),
159
+ self.selected_file_text,
160
+ ]),
161
+ padding=10,
162
+ )
163
+
164
+ transcription_engines = ["whisperx", "whisper"]
165
+ transcription_models = ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo"]
166
+ compute_types = ["auto", "int8", "float16", "float32"]
167
+ devices = ["auto", "cpu", "cuda"]
168
+ languages = ["auto", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"]
169
+ video_codecs = ["h264", "libx264", "h264_vaapi", "h264_nvenc", "hevc", "libx265", "hevc_vaapi"]
170
+ audio_codecs = ["aac", "libopus", "mp3", "vorbis"]
171
+
172
+ transcription_engine = ft.Dropdown(
173
+ label=i18n("Transcription Engine"),
174
+ options=[ft.dropdown.Option(e) for e in transcription_engines],
175
+ value="whisperx",
176
+ expand=1
177
+ )
178
+
179
+ transcription_model = ft.Dropdown(
180
+ label=i18n("Model"),
181
+ options=[ft.dropdown.Option(m) for m in transcription_models],
182
+ value="medium",
183
+ expand=1
184
+ )
185
+
186
+ compute_type = ft.Dropdown(
187
+ label=i18n("Compute Type"),
188
+ options=[ft.dropdown.Option(t) for t in compute_types],
189
+ value="auto",
190
+ expand=1
191
+ )
192
+
193
+ device = ft.Dropdown(
194
+ label=i18n("Device"),
195
+ options=[ft.dropdown.Option(d) for d in devices],
196
+ value="auto",
197
+ expand=1
198
+ )
199
+
200
+ batch_size = ft.TextField(
201
+ label=i18n("Batch Size"),
202
+ value="4",
203
+ expand=1,
204
+ input_filter=ft.NumbersOnlyInputFilter()
205
+ )
206
+
207
+ input_lang = ft.Dropdown(
208
+ label=i18n("Input Language"),
209
+ options=[ft.dropdown.Option(l) for l in languages],
210
+ value="auto",
211
+ expand=1
212
+ )
213
+
214
+ translate_lang = ft.Dropdown(
215
+ label=i18n("Translate to"),
216
+ options=[ft.dropdown.Option(l) for l in languages],
217
+ value="none",
218
+ expand=1
219
+ )
220
+
221
+ video_codec = ft.Dropdown(
222
+ label=i18n("Video Codec"),
223
+ options=[ft.dropdown.Option(c) for c in video_codecs],
224
+ value="h264",
225
+ expand=1
226
+ )
227
+
228
+ audio_codec = ft.Dropdown(
229
+ label=i18n("Audio Codec"),
230
+ options=[ft.dropdown.Option(c) for c in audio_codecs],
231
+ value="aac",
232
+ expand=1
233
+ )
234
+
235
+ normalize = ft.Checkbox(label=i18n("Normalize folder times"), value=False)
236
+ overwrite = ft.Checkbox(label=i18n("Overwrite existing files"), value=False)
237
+ copy_files = ft.Checkbox(label=i18n("Copy non-video files"), value=False)
238
+ disable_srt = ft.Checkbox(label=i18n("Disable SRT generation"), value=False)
239
+ disable_softsubs = ft.Checkbox(label=i18n("Disable softsubs"), value=False)
240
+ disable_hardsubs = ft.Checkbox(label=i18n("Disable hardsubs"), value=False)
241
+
242
+ output_softsubs_path = ft.TextField(
243
+ label=i18n("Softsubs Output Path"),
244
+ value="softsubs_output",
245
+ expand=1
246
+ )
247
+ output_hardsubs_path = ft.TextField(
248
+ label=i18n("Hardsubs Output Path"),
249
+ value="hardsubs_output",
250
+ expand=1
251
+ )
252
+
253
+ output_paths = ft.Container(
254
+ content=ft.Column([
255
+ ft.Row([
256
+ output_softsubs_path,
257
+ ft.ElevatedButton(i18n("Browse"), on_click=lambda _: softsubs_folder_picker.get_directory_path()),
258
+ ]),
259
+ ft.Row([
260
+ output_hardsubs_path,
261
+ ft.ElevatedButton(i18n("Browse"), on_click=lambda _: hardsubs_folder_picker.get_directory_path()),
262
+ ]),
263
+ ]),
264
+ padding=10,
265
+ )
266
+
267
+ async def show_alert(msg: str, color: str = "error"):
268
+ banner = ft.Banner(
269
+ bgcolor=color,
270
+ leading=ft.Icon(ft.icons.WARNING_AMBER_ROUNDED if color == "error" else ft.icons.INFO),
271
+ content=ft.Text(msg),
272
+ actions=[
273
+ ft.TextButton("Ok", on_click=lambda _: self.page.overlay.remove(banner)),
274
+ ],
275
+ )
276
+ self.page.overlay.append(banner)
277
+ await page.update_async()
278
+
279
+ async def stop_processing():
280
+ if self.current_process:
281
+ self.current_process.terminate()
282
+ self.current_process = None
283
+ self.processing = False
284
+ self.run_button.text = i18n("Run LeGen")
285
+ await page.update_async()
286
+ await show_alert(i18n("Processing stopped by user"), "info")
287
+ await update_progress(False)
288
+
289
+ async def update_progress(visible: bool, progress: float = 0):
290
+ self.progress.visible = visible
291
+ self.progress_text.visible = visible
292
+ if visible:
293
+ self.progress.value = progress
294
+ await page.update_async()
295
+
296
+
297
+ async def update_ui(text):
298
+ if not self.progress_text:
299
+ return
300
+ self.progress_text.value = text
301
+ await page.update_async()
302
+
303
+
304
+ import locale
305
+
306
+ def process_in_thread(cmd):
307
+ print(f"Executing command: {' '.join(cmd)}")
308
+
309
+ loop = asyncio.new_event_loop()
310
+ asyncio.set_event_loop(loop)
311
+
312
+ try:
313
+ self.current_process = subprocess.Popen(
314
+ cmd,
315
+ stdout=subprocess.PIPE,
316
+ stderr=subprocess.PIPE, # Redireciona stderr também
317
+ text=True,
318
+ encoding='utf-8',
319
+ bufsize=1, # Linha a linha
320
+ universal_newlines=True
321
+ )
322
+
323
+
324
+
325
+
326
+ async def read_output():
327
+ final_message = None # Variável para armazenar a mensagem final
328
+ while True:
329
+ if self.current_process is None:
330
+ break
331
+
332
+ # Leitura de stdout
333
+ output = self.current_process.stdout.readline()
334
+ if output:
335
+ print(f"{output.strip()}")
336
+ #print(f"Process output (with ANSI): {output.strip()}")
337
+ clean_line, progress_value = process_output(output.strip())
338
+
339
+ # Verifica se a mensagem final está presente e armazena
340
+ if "⌛ Processing files for" in clean_line:
341
+ final_message = clean_line # Armazena a mensagem final
342
+
343
+ await update_ui(clean_line)
344
+ if progress_value is not None:
345
+ await update_progress(True, progress_value)
346
+
347
+ # Leitura de stderr (para capturar possíveis erros do FFmpeg)
348
+ error_output = self.current_process.stderr.readline()
349
+ if error_output:
350
+ #print(f"Process error: {error_output.strip()}") # Exibe stderr no terminal
351
+ clean_line, _ = process_output(error_output.strip())
352
+ await update_ui(clean_line)
353
+
354
+ # Verifica se o processo terminou
355
+ if output == '' and error_output == '' and self.current_process.poll() is not None:
356
+ break
357
+
358
+ # Após a conclusão, exibe a mensagem final, se ela existir
359
+ if final_message:
360
+ await update_ui(final_message)
361
+
362
+
363
+
364
+
365
+
366
+
367
+ loop.run_until_complete(read_output())
368
+
369
+ if self.current_process:
370
+ returncode = self.current_process.poll()
371
+ if returncode is None:
372
+ self.current_process.terminate()
373
+ self.current_process.wait()
374
+
375
+ stdout, stderr = self.current_process.communicate()
376
+
377
+ loop.run_until_complete(update_progress(False))
378
+
379
+ if returncode == 0:
380
+ loop.run_until_complete(show_alert("Processing completed successfully!", "success"))
381
+ else:
382
+ print(f"Process error: {stderr}")
383
+ loop.run_until_complete(show_alert(f"Error: {stderr}"))
384
+
385
+ except Exception as e:
386
+ print(f"Exception occurred: {str(e)}")
387
+ loop.run_until_complete(update_progress(False))
388
+ loop.run_until_complete(show_alert(f"Error: {str(e)}"))
389
+
390
+ finally:
391
+ loop.close()
392
+ async def reset_ui():
393
+ self.processing = False
394
+ self.run_button.text = "Run LeGen"
395
+ await page.update_async()
396
+ loop.run_until_complete(reset_ui())
397
+
398
+ async def _reset_button():
399
+ self.processing = False
400
+ self.run_button.text = "Run LeGen"
401
+ await self.page.update_async()
402
+
403
+ async def run_legen(e):
404
+ if self.processing:
405
+ await stop_processing()
406
+ return
407
+
408
+ if not self.input_path:
409
+ await show_alert(i18n("Please select a folder"))
410
+ return
411
+
412
+ if not os.path.exists(str(self.input_path)):
413
+ await show_alert(i18n("Selected folder path does not exist"))
414
+ return
415
+
416
+ if not os.path.exists("legen.py"):
417
+ await show_alert(i18n("legen.py not found in current directory"))
418
+ return
419
+
420
+ cmd = ["python", "legen.py", "-i", str(self.input_path)]
421
+
422
+ if normalize.value:
423
+ cmd.append("--norm")
424
+ if overwrite.value:
425
+ cmd.append("--overwrite")
426
+ if copy_files.value:
427
+ cmd.append("--copy_files")
428
+ if disable_srt.value:
429
+ cmd.append("--disable_srt")
430
+ if disable_softsubs.value:
431
+ cmd.append("--disable_softsubs")
432
+ if disable_hardsubs.value:
433
+ cmd.append("--disable_hardsubs")
434
+
435
+ cmd.extend(["-ts:e", transcription_engine.value])
436
+ cmd.extend(["-ts:m", transcription_model.value])
437
+ cmd.extend(["-ts:d", device.value])
438
+ cmd.extend(["-ts:c", compute_type.value])
439
+ cmd.extend(["-ts:b", batch_size.value])
440
+
441
+ if translate_lang.value != "none":
442
+ cmd.extend(["--translate", translate_lang.value])
443
+ if input_lang.value != "auto":
444
+ cmd.extend(["--input_lang", input_lang.value])
445
+
446
+ cmd.extend(["-c:v", video_codec.value])
447
+ cmd.extend(["-c:a", audio_codec.value])
448
+
449
+ if output_softsubs_path.value:
450
+ cmd.extend(["-o:s", output_softsubs_path.value])
451
+ if output_hardsubs_path.value:
452
+ cmd.extend(["-o:h", output_hardsubs_path.value])
453
+
454
+ self.processing = True
455
+ self.run_button.text = i18n("Stop LeGen")
456
+ self.page.update()
457
+
458
+ try:
459
+ await update_progress(True, 0)
460
+ await asyncio.get_event_loop().run_in_executor(None, process_in_thread, cmd)
461
+ except Exception as e:
462
+ #print(f"Error during execution: {str(e)}")
463
+ await show_alert(f"Error during execution: {str(e)}")
464
+ finally:
465
+ self.processing = False
466
+ self.run_button.text = i18n("Run LeGen")
467
+ await update_progress(False)
468
+ #await page.update_async() # Ocultar a barra de progresso após a conclusão
469
+
470
+ # Você pode adicionar um alerta ou mensagem final aqui se necessário
471
+ await show_alert("Processing has finished.", "info")
472
+
473
+
474
+ # A seção do layout pode ficar inalterada a menos que você precise de alterações.
475
+ # Progress bar configuration
476
+ self.progress = ft.ProgressBar(width=400, color="blue", visible=False, value=0)
477
+ self.progress_text = ft.Text(i18n("Processing..."), visible=False)
478
+
479
+ progress_section = ft.Container(
480
+ content=ft.Column([
481
+ self.progress,
482
+ self.progress_text,
483
+ ])
484
+ )
485
+
486
+ self.run_button = ft.ElevatedButton(i18n("Run LeGen"), on_click=run_legen, width=200)
487
+
488
+ content = ft.Container(
489
+ content=ft.Column([
490
+ ft.Row([
491
+ ft.Text("LeGen UI", size=30, weight=ft.FontWeight.BOLD),
492
+ ft.Row([
493
+ ft.ElevatedButton(
494
+ "Créditos",
495
+ on_click=show_credits,
496
+ icon=ft.icons.INFO
497
+ ),
498
+ ft.IconButton(
499
+ icon=ft.icons.DARK_MODE if not self.dark_mode else ft.icons.LIGHT_MODE,
500
+ on_click=toggle_dark_mode,
501
+ ),
502
+ ]),
503
+ ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN),
504
+ input_section,
505
+ ft.Divider(),
506
+ ft.Text(i18n("Transcription Settings"), size=20, weight=ft.FontWeight.BOLD),
507
+ ft.ResponsiveRow([
508
+ ft.Column([transcription_engine], col=6),
509
+ ft.Column([transcription_model], col=6),
510
+ ]),
511
+ ft.ResponsiveRow([
512
+ ft.Column([compute_type], col=6),
513
+ ft.Column([device], col=6),
514
+ ]),
515
+ ft.ResponsiveRow([
516
+ ft.Column([batch_size], col=6),
517
+ ft.Column([input_lang], col=6),
518
+ ]),
519
+ ft.ResponsiveRow([
520
+ ft.Column([translate_lang], col=6),
521
+ ]),
522
+ ft.Divider(),
523
+ ft.Text(i18n("Output Settings"), size=20, weight=ft.FontWeight.BOLD),
524
+ ft.ResponsiveRow([
525
+ ft.Column([video_codec], col=6),
526
+ ft.Column([audio_codec], col=6),
527
+ ]),
528
+ output_paths,
529
+ ft.Divider(),
530
+ ft.Text(i18n("Options"), size=20, weight=ft.FontWeight.BOLD),
531
+ ft.ResponsiveRow([
532
+ ft.Column([normalize], col=4),
533
+ ft.Column([overwrite], col=4),
534
+ ft.Column([copy_files], col=4),
535
+ ]),
536
+ ft.ResponsiveRow([
537
+ ft.Column([disable_srt], col=4),
538
+ ft.Column([disable_softsubs], col=4),
539
+ ft.Column([disable_hardsubs], col=4),
540
+ ]),
541
+ ft.Divider(),
542
+ progress_section,
543
+ ft.ElevatedButton(i18n("Run LeGen"), on_click=run_legen, width=200),
544
+ ]),
545
+ padding=20
546
+ )
547
+
548
+ # Add content to a scrollable container
549
+ page.add(
550
+ ft.Container(
551
+ content=content,
552
+ expand=True,
553
+ )
554
+ )
555
+
556
+ if __name__ == '__main__':
557
+ app = LeGenUI()
558
+ ft.app(target=app.main)
utils.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from pathlib import Path
3
+
4
+ from contextlib import contextmanager
5
+
6
+
7
+ @contextmanager
8
+ def time_task(message_start=None, end=' ', message="⏱ Took"):
9
+ if message_start:
10
+ print(message_start, end=end, flush=True)
11
+ start_time = time.time()
12
+ yield
13
+ end_time = time.time()
14
+ elapsed_time = end_time - start_time
15
+ formatted_elapsed_time = format_time(elapsed_time)
16
+ print(f"{message} {formatted_elapsed_time}", flush=True)
17
+
18
+
19
+ def format_time(elapsed_time):
20
+ hours, rem = divmod(elapsed_time, 3600)
21
+ minutes, seconds = divmod(rem, 60)
22
+
23
+ # Check and format the non-zero time units
24
+ parts = []
25
+ if hours:
26
+ parts.append(f"{int(hours)}h")
27
+ if minutes:
28
+ parts.append(f"{int(minutes)}m")
29
+ if seconds or not parts:
30
+ # Add seconds if it's the only non-zero unit or if all units are zero
31
+ parts.append(f"{int(seconds)}s")
32
+
33
+ return ' '.join(parts)
34
+
35
+
36
+ def time_func(func):
37
+ def wrapper(*args, **kwargs):
38
+ start_time = time.time()
39
+ result = func(*args, **kwargs)
40
+ end_time = time.time()
41
+ elapsed_time = end_time - start_time
42
+ formatted_elapsed_time = format_time(elapsed_time)
43
+ print(f"Execution time of {func.__name__}: {formatted_elapsed_time}")
44
+ return result
45
+ return wrapper
46
+
47
+ def check_other_extensions(file_path, extensions_to_check):
48
+ """
49
+ Check the existence of files with the same name but different extensions
50
+ in the same folder.
51
+
52
+ Parameters:
53
+ - file_path (str): The path of the file to check.
54
+ - extensions_to_check (list): List of extensions to check.
55
+
56
+ Returns:
57
+ - list: List of existing file paths with different extensions.
58
+ """
59
+ file_path = Path(file_path)
60
+ folder = file_path.parent
61
+ base_name = file_path.stem
62
+
63
+ matching_files = [
64
+ folder / (base_name + ext)
65
+ for ext in extensions_to_check
66
+ if (folder / (base_name + ext)).exists()
67
+ ]
68
+
69
+ return matching_files
70
+
71
+ video_extensions = {".mp4", ".webm", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".vob", ".mts", ".m2ts", ".ts", ".yuv", ".mpg", ".mp2", ".mpeg", ".mpe", ".mpv", ".m2v", ".m4v", ".3gp", ".3g2", ".nsv", ".mts"}
72
+ audio_extensions = {".aa", ".aac", ".aax", ".act", ".aiff", ".alac", ".amr", ".ape", ".au", ".awb", ".dss", ".dvf", ".flac", ".gsm", ".iklax", ".ivs", ".m4a", ".m4b", ".m4p", ".mpga", ".mmf", ".mp3", ".mpc", ".msv", ".nmf", ".ogg", ".oga", ".mogg", ".opus", ".ra", ".rm", ".raw", ".rf64", ".sln", ".tta", ".voc", ".vox", ".wav", ".wma", ".wv", ".webm", ".8svx"}
whisper_utils.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import pysrt
5
+ import whisper
6
+ import whisper.transcribe
7
+ import whisperx
8
+ import subtitle_utils
9
+ from utils import time_task
10
+
11
+
12
+ def transcribe_audio(model: whisper.model, audio_path: Path, srt_path: Path, lang: str = None, disable_fp16: bool = False):
13
+ # Load audio
14
+ audio = whisper.load_audio(file=audio_path.as_posix())
15
+
16
+ # Transcribe
17
+ with time_task():
18
+ transcribe = model.transcribe(audio=audio, language=lang, fp16=False if disable_fp16 else True, verbose=False)
19
+
20
+ # Align if possible
21
+ if lang in whisperx.alignment.DEFAULT_ALIGN_MODELS_HF or lang in whisperx.alignment.DEFAULT_ALIGN_MODELS_TORCH:
22
+ with time_task(message_start="Running alignment..."):
23
+ try:
24
+ model_a, metadata = whisperx.load_align_model(language_code=lang, device="cuda")
25
+ transcribe = whisperx.align(transcript=transcribe["segments"], model=model_a, align_model_metadata=metadata, audio=audio, device="cuda", return_char_alignments=True)
26
+ except Exception:
27
+ model_a, metadata = whisperx.load_align_model(language_code=lang, device="cpu") # force load on cpu due errors on gpu
28
+ transcribe = whisperx.align(transcript=transcribe["segments"], model=model_a, align_model_metadata=metadata, audio=audio, device="cpu", return_char_alignments=True)
29
+ else:
30
+ print(f"Language {lang} not suported for alignment. Skipping this step")
31
+
32
+ # Format subtitles
33
+ segments = subtitle_utils.format_segments(transcribe['segments'])
34
+
35
+ # Save the subtitle file
36
+ subtitle_utils.SaveSegmentsToSrt(segments, srt_path)
37
+
38
+ return transcribe
39
+
40
+
41
+ def detect_language(model: str, audio_path: Path):
42
+ # load audio and pad/trim it to fit 30 seconds
43
+ audio = whisper.load_audio(audio_path.as_posix())
44
+ audio = whisper.pad_or_trim(audio)
45
+ # make log-Mel spectrogram and move to the same device as the model
46
+ mel = whisper.log_mel_spectrogram(audio).to(model.device)
47
+
48
+ # detect the spoken language
49
+ _, probs = model.detect_language(mel)
50
+ return max(probs, key=probs.get)
whisperx_utils.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import whisperx
5
+ import whisper # only for detect language
6
+
7
+ import whisper_utils
8
+ import subtitle_utils
9
+ from utils import time_task
10
+
11
+ def transcribe_audio(model: whisperx.asr.WhisperModel, audio_path: Path, srt_path: Path, lang: str = None, device: str = "cpu", batch_size: int = 4):
12
+ audio = whisperx.load_audio(file=audio_path.as_posix(), sr=model.model.feature_extractor.sampling_rate)
13
+
14
+ # Define the progress callback function
15
+ def progress_callback(state, current: int = None, total: int = None):
16
+ args = state, current, total
17
+ args = [arg for arg in args if arg is not None]
18
+
19
+ if len(args) == 1:
20
+ state = args[0]
21
+ if len(args) > 1:
22
+ total = args[-1]
23
+ current = args[-2]
24
+ state = None
25
+ if len(args) > 2:
26
+ state = args[-3]
27
+
28
+ try:
29
+ if state is None:
30
+ state = "WhisperX"
31
+ elif type(state) == 'String' or type(state) == int:
32
+ state = state
33
+ else:
34
+ state = state.value
35
+ except:
36
+ state = "WhisperX"
37
+
38
+ print('\r \r' + state + ((': ' + str(round(current/total*100)) + '%') if current and total else '') + ((' [' + str(current) + '/' + str(total) + ']') if current and total else ''), end=' ', flush=True)
39
+
40
+ # Transcribe
41
+ with time_task("Running WhisperX transcription engine...", end='\n'):
42
+ transcribe = model.transcribe(audio=audio, language=lang, batch_size=batch_size, on_progress=progress_callback)
43
+
44
+ # Align if possible
45
+ if lang in whisperx.alignment.DEFAULT_ALIGN_MODELS_HF or lang in whisperx.alignment.DEFAULT_ALIGN_MODELS_TORCH:
46
+ with time_task(message_start="Running alignment...", end='\n'):
47
+ try:
48
+ model_a, metadata = whisperx.load_align_model(language_code=lang, device="cuda")
49
+ transcribe = whisperx.align(transcript=transcribe["segments"], model=model_a, align_model_metadata=metadata, audio=audio, device="cuda", return_char_alignments=True, on_progress=progress_callback)
50
+ except Exception:
51
+ model_a, metadata = whisperx.load_align_model(language_code=lang, device="cpu") # force load on cpu due errors on gpu
52
+ transcribe = whisperx.align(transcript=transcribe["segments"], model=model_a, align_model_metadata=metadata, audio=audio, device="cpu", return_char_alignments=True, on_progress=progress_callback)
53
+ else:
54
+ print(f"Language {lang} not suported for alignment. Skipping this step")
55
+
56
+ # Format subtitles
57
+ segments = subtitle_utils.format_segments(transcribe['segments'])
58
+
59
+ # Save the subtitle file
60
+ subtitle_utils.SaveSegmentsToSrt(segments, srt_path)
61
+
62
+ return transcribe
63
+
64
+
65
+ def detect_language(model: whisperx.asr.WhisperModel, audio_path: Path):
66
+ try:
67
+ if os.getenv("COLAB_RELEASE_TAG"):
68
+ raise Exception("Method invalid for Google Colab")
69
+ audio = whisperx.load_audio(audio_path.as_posix(), model.model.feature_extractor.sampling_rate)
70
+ audio = whisper.pad_or_trim(audio, model.model.feature_extractor.n_samples)
71
+ mel = whisperx.asr.log_mel_spectrogram(audio, n_mels=model.model.model.n_mels)
72
+ encoder_output = model.model.encode(mel)
73
+ results = model.model.model.detect_language(encoder_output)
74
+ language_token, language_probability = results[0][0]
75
+ return language_token[2:-2]
76
+ except:
77
+ print("using whisper base model for detection: ", end='')
78
+ whisper_model = whisper.load_model("base", device="cpu", in_memory=True)
79
+ return whisper_utils.detect_language(model=whisper_model, audio_path=audio_path)