TranscribeTools 0.5.5__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from .transcribe_folder import process_file, cli
2
+
3
+ __all__ = ["process_file", "cli"]
4
+
5
+ __version__ = "0.5.4" # It MUST match the version in pyproject.toml file
@@ -0,0 +1,5 @@
1
+ from transcribetools.transcribe_folder import cli
2
+
3
+ if __name__ == '__main__':
4
+ cli()
5
+ # console = rich.console.Console(width=120, force_terminal=True)
@@ -0,0 +1,2 @@
1
+ folder = "/Users/ncdegroot/Library/CloudStorage/OneDrive-Gedeeldebibliotheken-TilburgUniversity/Project - Reflective cafe - data"
2
+ model = "large"
@@ -0,0 +1,185 @@
1
+ from datetime import datetime
2
+ import logging
3
+ from pathlib import Path
4
+ import tkinter as tk
5
+ from tkinter.filedialog import askdirectory
6
+ # from tkinter import messagebox as mb
7
+ import pymsgbox as msgbox
8
+ import toml
9
+ import whisper
10
+ import rich
11
+ from rich.prompt import Prompt
12
+ import rich_click as click
13
+ from result import Result, is_ok, is_err, Ok, Err
14
+ from .local_wisper_model import save_config_to_toml, get_config_from_toml, ask_choice, show_config, console
15
+
16
+ # logging.getLogger("python3").setLevel(logging.ERROR)
17
+ # loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
18
+ # tk bug in sequoia
19
+ # import sys
20
+ # sys.stderr = open("log", "w", buffering=1)
21
+ # can't find the 'python3' logger to silence
22
+
23
+ MODEL = "large"
24
+ # LOCALPATH = ('/Users/ncdegroot/Library/CloudStorage/'
25
+ # 'OneDrive-Gedeeldebibliotheken-TilburgUniversity/'
26
+ # 'Project - Reflective cafe - data')
27
+ LOCALPATH = Path.cwd()
28
+ model = None
29
+
30
+
31
+ def process_file(path):
32
+ output_path = path.with_suffix('.txt')
33
+ try:
34
+ print("Start processing...")
35
+ result = model.transcribe(str(path), verbose=True)
36
+ # false: only progressbar; true: all; no param: no feedback
37
+ except Exception as e:
38
+ print(f"Error while processing {path}: '{e}'. Please fix it")
39
+ else:
40
+ text_to_save = result["text"]
41
+ print(text_to_save)
42
+
43
+ # file_name = f"{data_file.split('.')[0]}_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.txt"
44
+ # file_name = output_path
45
+ # Open the file in write mode
46
+ with open(output_path, 'w') as file:
47
+ # Write the text to the file
48
+ file.write(text_to_save)
49
+
50
+ print(f'Text has been saved to {output_path}')
51
+
52
+
53
+ @click.group(no_args_is_help=True,
54
+ epilog='Check out the docs at https://gitlab.uvt.nl/tst-research/transcribetools for more details')
55
+ @click.version_option(package_name='transcribetools')
56
+ @click.pass_context # our 'global' context
57
+ @click.option("--configfilename",
58
+ default="localwhisper.toml",
59
+ help="Specify config file to use",
60
+ show_default=True,
61
+ metavar="FILE",
62
+ type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
63
+ show_choices=False,
64
+ required=False,
65
+ prompt="Enter config filename",
66
+ )
67
+ def cli(ctx: click.Context, configfilename):
68
+ global model
69
+ # open config, ask for values if needed:
70
+ # Prompt.ask(msg)
71
+ home = Path.home()
72
+ config_path = home / configfilename
73
+ if not config_path.exists():
74
+ save_config_to_toml(config_path, LOCALPATH, MODEL)
75
+ result = get_config_from_toml(config_path)
76
+ if is_err(result):
77
+ click.echo(f"Exiting due to {result.err}")
78
+ exit(1)
79
+ config = result.ok_value
80
+ if config:
81
+ # click.echo("Config")
82
+ click.echo(f"Config filename: {config_path}")
83
+ # click.echo(f"Folder path for soundfiles: {config.folder}")
84
+ # click.echo(f"Transcription model name: {config.model}")
85
+
86
+ ctx.obj = config
87
+ # process_files(config)
88
+
89
+
90
+ # the `cli` subcommand 'process'
91
+
92
+ @cli.command("process", help="Using current configuration, transcribe all soundfiles in the folder")
93
+ # @click.option("--filename",
94
+ # default="localwhisper.toml",
95
+ # help="Specify config file to use",
96
+ # show_default=True,
97
+ # metavar="FILE",
98
+ # type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
99
+ # show_choices=False,
100
+ # required=False,
101
+ # prompt="Enter config file name",
102
+ # )
103
+ @click.pass_obj # in casu the config obj
104
+ def process(config):
105
+ global model
106
+ # config = config
107
+ model = whisper.load_model(config.model)
108
+ soundfiles_path = Path(config.folder)
109
+ txt_files = [file for file in soundfiles_path.glob('*') if file.suffix.lower() == '.txt']
110
+ file_stems = [file.stem for file in txt_files]
111
+ # a txt file_stem indicates mp3 has been processed already
112
+ mp3_files = [file for file in soundfiles_path.glob('*') if file.suffix.lower() == '.mp3' and
113
+ file.stem not in file_stems]
114
+ click.echo(f"{len(mp3_files)} files to be processed")
115
+ for file in mp3_files:
116
+ click.echo(f"Processing {file}")
117
+ process_file(file)
118
+
119
+
120
+ # the `cli` command config
121
+ @cli.group("config")
122
+ def config():
123
+ pass
124
+
125
+
126
+ # the `config` create subcommand
127
+ @click.command("create", help="Create new configuration file")
128
+ def create():
129
+ msg = "Select folder to monitor containing the sound files"
130
+ click.echo(msg)
131
+ # root = tk.Tk()
132
+ # root.focus_force()
133
+ # Cause the root window to disappear milliseconds after calling the filedialog.
134
+ # root.after(100, root.withdraw)
135
+ # tk.Tk().withdraw()
136
+ # hangs: mb.showinfo("msg","Select folder containing the sound files")
137
+ msgbox.alert(msg, "info")
138
+ # "title" only supported on linux ith wv ...
139
+ folder = askdirectory(title="Select folder to monitor containing the sound files",
140
+ mustexist=True,
141
+ initialdir='~')
142
+ choices = ["tiny", "base", "small", "medium", "large"]
143
+ # inx = ask_choice("Choose a model", choices)
144
+ # model = choices[inx]
145
+ model = Prompt.ask("Choose a model",
146
+ console=console,
147
+ choices=choices,
148
+ show_default=True,
149
+ default="large")
150
+ config_name = Prompt.ask("Enter a name for the configuration file",
151
+ show_default=True,
152
+ default="localwhisper.toml")
153
+ config_path = Path(config_name)
154
+ toml_path = config_path.with_suffix(".toml")
155
+ while toml_path.exists(): # current dir
156
+ result = get_config_from_toml(toml_path)
157
+ click.secho("Already exists...", fg='red')
158
+ show_config(result)
159
+ overwrite = Prompt.ask("Overwrite?",
160
+ choices=["y", "n"],
161
+ default="n",
162
+ show_default=True)
163
+ if overwrite == "y":
164
+ break
165
+ else:
166
+ return
167
+ # Prompt.ask("Enter model name")
168
+ save_config_to_toml(toml_path, folder, model)
169
+ click.echo(f"{toml_path} saved")
170
+
171
+
172
+ # the 'config' show subcommand
173
+ @click.command("show", help="Show current configuration file")
174
+ @click.pass_obj
175
+ def show(config):
176
+ click.echo(f"Config folder path: {config.folder}")
177
+ click.echo(f"Config model name: {config.model}")
178
+
179
+
180
+ # connect the subcommand to `config'
181
+ config.add_command(create)
182
+ config.add_command(show)
183
+
184
+ if __name__ == "__main__":
185
+ cli()
@@ -0,0 +1,73 @@
1
+ import toml
2
+ from result import is_ok, is_err, Ok, Err, Result
3
+ from attrs import define
4
+ from rich.console import Console
5
+
6
+ console = Console(width=120, force_terminal=True)
7
+
8
+
9
+ @define
10
+ class Config:
11
+ folder: str
12
+ model: str
13
+
14
+
15
+ def save_config_to_toml(filepath,
16
+ folder_name="",
17
+ model_name=""):
18
+ try:
19
+ data = {"folder": folder_name, "model": model_name}
20
+ with open(filepath, 'w') as toml_file:
21
+ # noinspection PyTypeChecker
22
+ toml.dump(data, toml_file)
23
+ except Exception as e:
24
+ print(f"Error saving config to TOML file: {e}")
25
+
26
+
27
+ def get_config_from_toml(filepath) -> Result:
28
+ try:
29
+ with open(filepath, 'r') as toml_file:
30
+ data = toml.load(toml_file)
31
+ except FileNotFoundError:
32
+ Err("TOML file not found.")
33
+ except toml.TomlDecodeError:
34
+ Err("Error decoding TOML file.")
35
+ except Exception as e:
36
+ Err(f"Unexpected error: {e}")
37
+ else:
38
+ config = Config(**data) # as data is flat, it's ok
39
+ return Ok(config)
40
+
41
+
42
+ def ask_choice(msg: str, choices) -> int:
43
+
44
+ # Print het keuzemenu
45
+ console.print(
46
+ f"[bold magenta]{msg}[/bold magenta]\n"
47
+ "[yellow]Kies een van de volgende opties:[/yellow]"
48
+ )
49
+ for i, choice in enumerate(choices, start=1):
50
+ console.print(f"{i}. {choice}")
51
+
52
+ # Vraag input van de gebruiker
53
+ user_input = Prompt.ask(
54
+ "Voer het nummer van je keuze in",
55
+ choices=[str(i) for i in range(1, len(choices) + 1)]
56
+ )
57
+
58
+ # Verwerk de keuze
59
+ chosen_option = choices[int(user_input) - 1] # Converteer input naar index
60
+ console.print(f"[green]Je hebt gekozen voor:[/green] {chosen_option}")
61
+
62
+ return chosen_option
63
+
64
+
65
+ def show_config(result: Result):
66
+ if is_err(result):
67
+ print(f"Exiting due to {result.err}")
68
+ return False
69
+ config = result.ok_value
70
+ if config:
71
+ print(f"Config folder path: {config.folder}")
72
+ print(f"Config model name: {config.model}")
73
+ return True
@@ -0,0 +1,423 @@
1
+ import time
2
+ from pathlib import Path
3
+
4
+ # import tkinter as tk
5
+ from tkinter.filedialog import askdirectory
6
+
7
+ # from tkinter import messagebox as mb
8
+ import pymsgbox as msgbox
9
+
10
+ # import toml
11
+ import whisper
12
+
13
+ # import rich
14
+ from rich.prompt import Prompt
15
+ import rich_click as click
16
+ from result import Result, is_ok, is_err, Ok, Err # noqa: F401
17
+ import soundfile as sf
18
+
19
+ from .transcribe_folder_model import (
20
+ save_config_to_toml,
21
+ get_config_from_toml,
22
+ show_config,
23
+ console,
24
+ )
25
+
26
+ # logging.getLogger("python3").setLevel(logging.ERROR)
27
+ # loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
28
+ # tk bug in sequoia
29
+ # import sys
30
+ # sys.stderr = open("log", "w", buffering=1)
31
+ # can't find the 'python3' logger to silence
32
+
33
+ MODEL = "large"
34
+ # LOCALPATH = ('/Users/ncdegroot/Library/CloudStorage/'
35
+ # 'OneDrive-Gedeeldebibliotheken-TilburgUniversity/'
36
+ # 'Project - Reflective cafe - data')
37
+ LOCALPATH = Path.cwd()
38
+ model = None
39
+
40
+
41
+ def process_file(path, args):
42
+ """open file, transcribe using args and save to file"""
43
+ output_path = path.with_suffix(".txt")
44
+ try:
45
+ click.echo("Start processing...")
46
+ result = model.transcribe(
47
+ str(path),
48
+ verbose=True,
49
+ **args,
50
+ )
51
+ # false: only progressbar; true: all; no param: no feedback
52
+ except Exception as e:
53
+ click.echo(f"Error while processing {path}: '{e}'. Please fix it")
54
+ else:
55
+ text_to_save = result["text"]
56
+ click.echo(text_to_save)
57
+
58
+ # file_name = f"{data_file.split('.')[0]}_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.txt"
59
+ # file_name = output_path
60
+ # Open the file in write mode
61
+ with open(output_path, "w") as file:
62
+ # Write the text to the file
63
+ file.write(text_to_save)
64
+
65
+ click.echo(f"Text has been saved to {output_path}")
66
+
67
+
68
+ def translate_it(input_path: Path, translator, args):
69
+ """open the file on this path, translate using args and save to file"""
70
+ output_path = input_path.with_stem(
71
+ str(input_path.stem).replace(args["source_lang"], args["target_lang"])
72
+ )
73
+ # else
74
+ if args["target_lang"] not in input_path.stem:
75
+ output_path = input_path.with_stem(input_path.stem + "-" + args["target_lang"])
76
+
77
+ # if doc(x) or other formatted files
78
+ if input_path.suffix != ".txt":
79
+ # Using translate_document_from_filepath() with file paths
80
+ translator.translate_document_from_filepath(
81
+ input_path, output_path, **args
82
+ )
83
+ else: # txt
84
+ with open(input_path, "r", encoding="utf-8") as infile:
85
+
86
+ try:
87
+ click.echo("Start translating...")
88
+ result = translator.translate_text(
89
+ text=infile.read(),
90
+ **args,
91
+ )
92
+ # false: only progressbar; true: all; no param: no feedback
93
+ except Exception as e:
94
+ click.echo(f"Error while processing {input_path}: '{e}'. Please fix it")
95
+ else:
96
+ text_to_save = result.text
97
+ click.echo(text_to_save)
98
+
99
+ # file_name = f"{data_file.split('.')[0]}_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.txt"
100
+ # file_name = output_path
101
+ # Open the file in write mode
102
+ #
103
+ # existing replace
104
+
105
+ with open(output_path, "w") as outfile:
106
+ # Write the text to the file
107
+ outfile.write(text_to_save)
108
+
109
+ click.echo(f"Text has been saved to {output_path}")
110
+
111
+
112
+ @click.group(
113
+ no_args_is_help=True,
114
+ epilog="Use config --help or process --help to see options.\n"
115
+ "Check out the docs at https://gitlab.uvt.nl/tst-research/transcribetools "
116
+ "for more details",
117
+ )
118
+ @click.version_option(package_name="transcribetools")
119
+ @click.option(
120
+ "--debug/--no-debug",
121
+ "-d/-n",
122
+ help="Print debug messages and timing information",
123
+ default=False,
124
+ )
125
+ @click.pass_context # our 'global' context
126
+ @click.option(
127
+ "--configfilename",
128
+ "-c",
129
+ default=Path.home() / "localwhisper.toml",
130
+ help="Specify config file to use",
131
+ # show_default=True,
132
+ metavar="FILE",
133
+ type=click.Path(exists=True, dir_okay=False, readable=True, resolve_path=True),
134
+ show_choices=False,
135
+ required=False,
136
+ # prompt="Enter new config filename or accept default",
137
+ )
138
+ def cli(ctx: click.Context, debug, configfilename):
139
+ global model
140
+ # open config, ask for values if needed:
141
+ # Prompt.ask(msg)
142
+ home = Path.home()
143
+ config_path = home / configfilename
144
+ if debug:
145
+ click.echo(f"Config_path: {config_path}")
146
+ if not config_path.exists():
147
+ save_config_to_toml(config_path, LOCALPATH, MODEL)
148
+ result = get_config_from_toml(
149
+ config_path
150
+ ) # has the default values (homedir, large)
151
+ if is_err(result):
152
+ click.echo(f"Exiting due to {result.err}")
153
+ exit(1)
154
+ config = result.ok_value
155
+ if config:
156
+ # click.echo("Config")
157
+ click.echo(f"Config filename: {config_path}")
158
+ # click.echo(f"Folder path for soundfiles: {config.folder}")
159
+ # click.echo(f"Transcription model name: {config.model}")
160
+ config.debug = debug
161
+ ctx.obj = config
162
+ # process_files(config)
163
+
164
+
165
+ # the `cli` subcommand 'process'
166
+
167
+
168
+ @cli.command(
169
+ "transcribe",
170
+ help="Using current configuration, transcribe all soundfiles in the folder",
171
+ )
172
+ @click.option(
173
+ "--language",
174
+ "-l",
175
+ default="AUTO",
176
+ type=click.Choice(
177
+ ["nl", "en", "AUTO"],
178
+ case_sensitive=False,
179
+ ),
180
+ )
181
+ @click.option(
182
+ "--select_folder",
183
+ "-s",
184
+ default=False,
185
+ flag_value=True,
186
+ help="Override the path to the soundfiles from config, select a folder",
187
+ )
188
+ @click.option(
189
+ "--prompt",
190
+ "-p",
191
+ help='-p "" You can add special prompts and words (spelling) (max 224 chars) see '
192
+ "https://cookbook.openai.com/examples/whisper_prompting_guide",
193
+ )
194
+ @click.pass_obj # in casu the config obj
195
+ def transcribe(config, select_folder, prompt, language):
196
+ global model
197
+ # config = config
198
+ if config.debug:
199
+ click.echo(f"Load model: {config.model}")
200
+ model = whisper.load_model(config.model)
201
+ soundfiles_path = Path(config.folder)
202
+ if config.debug:
203
+ click.echo(f"Folder path for soundfiles: {soundfiles_path}")
204
+ click.echo(f"{language=}, {prompt=} ")
205
+
206
+ if select_folder:
207
+ soundfiles_path = Path(
208
+ askdirectory(
209
+ title="Select folder containing the sound files",
210
+ mustexist=True,
211
+ initialdir="~",
212
+ )
213
+ )
214
+
215
+ txt_files = [
216
+ file for file in soundfiles_path.glob("*") if file.suffix.lower() == ".txt"
217
+ ]
218
+ file_stems = [file.stem for file in txt_files]
219
+ # a txt file_stem indicates mp3 has been processed already (skip file with nio suffix
220
+ soundfiles = [
221
+ file
222
+ for file in soundfiles_path.glob("*")
223
+ if file.suffix.lower()
224
+ in (".mp3", "mp3", ".mp4", ".mpweg", ".mpga", ".m4a", ".wav", ".webm")
225
+ and file.stem not in file_stems
226
+ ]
227
+ click.echo(f"{len(soundfiles)} files to be processed")
228
+ duration = 0
229
+ start = time.perf_counter()
230
+
231
+ for file in soundfiles:
232
+ f, samplerate = sf.read(file)
233
+ duration += len(f) / samplerate
234
+ click.echo(f"Processing {file}")
235
+ args = dict()
236
+ if language != "AUTO":
237
+ args["language"] = language
238
+ if prompt:
239
+ args["prompt"] = prompt
240
+ process_file(file, args)
241
+ if soundfiles:
242
+ process_time = time.perf_counter() - start
243
+ click.echo(
244
+ f"Total sound duration: {duration:.1f} seconds, \n"
245
+ f"processing time: {process_time:.1f} seconds, \n"
246
+ f"realtime factor: {(process_time / duration):.2f}"
247
+ )
248
+
249
+
250
+ @cli.command(
251
+ "deeple_translate",
252
+ help="Using current configuration, translate all txt/doc/docx files in the folder",
253
+ )
254
+ @click.option(
255
+ "--source_language",
256
+ "-sl",
257
+ default="NL",
258
+ show_default=True,
259
+ type=click.Choice(
260
+ ["NL", "EN-GB", "EN-US", "AUTO"],
261
+ case_sensitive=False,
262
+ ),
263
+ )
264
+ @click.option(
265
+ "--target_language",
266
+ "-tl",
267
+ default="EN-GB",
268
+ type=click.Choice(
269
+ ["EN-GB", "EN-US", "NL"],
270
+ case_sensitive=False,
271
+ ),
272
+ )
273
+ @click.option(
274
+ "--select_folder",
275
+ "-s",
276
+ default=False,
277
+ flag_value=True,
278
+ help="Override the path to the files from config, select a folder",
279
+ )
280
+ @click.option(
281
+ "--prompt",
282
+ "-p",
283
+ help='-p "" You can add special prompts see https://www.deepl.com/en/pro-api',
284
+ )
285
+ @click.pass_obj # in casu the config obj
286
+ def deeple_translate(config, select_folder, prompt, source_language, target_language):
287
+ import deepl
288
+ import keyring as kr
289
+
290
+ if source_language == target_language:
291
+ raise click.BadParameter(f"Nothing to do {source_language} -> {target_language}")
292
+
293
+ valid_choices = ["EN-GB", "EN-US", "NL"]
294
+
295
+ if target_language not in valid_choices:
296
+ raise click.BadParameter(f"Invalid {target_language=} should be in {valid_choices}")
297
+
298
+ service_name = "DeeplAPI"
299
+ key = "auth_key"
300
+ # time.sleep(30)
301
+
302
+ auth_key = kr.get_password(service_name=service_name, username=key)
303
+ if auth_key is None:
304
+ key = Prompt.ask("Paste your auth key here")
305
+ kr.set_password(service_name=service_name, username=key, password=key)
306
+
307
+ translator = deepl.Translator(auth_key)
308
+
309
+ sourcefiles_path = Path(config.folder)
310
+ if config.debug:
311
+ click.echo(f"Folder path for sourcefiles: {sourcefiles_path}")
312
+ click.echo(f"{source_language=} -> {target_language=}, {prompt=} ")
313
+
314
+ if select_folder:
315
+ sourcefiles_path = Path(
316
+ askdirectory(
317
+ title="Select folder containing the source files",
318
+ mustexist=True,
319
+ initialdir="~",
320
+ )
321
+ )
322
+
323
+ translated_files = [
324
+ file
325
+ for file in sourcefiles_path.glob("*")
326
+ if f"{target_language}" in file.stem and file.suffix.lower() == ".txt"
327
+ ]
328
+ file_stems = [file.stem for file in translated_files]
329
+ # file has been processed already (skip file with no suffix
330
+ translate_file_paths = [
331
+ file
332
+ for file in sourcefiles_path.glob("*")
333
+ if file.suffix.lower() in (".txt", ".doc", ".docx")
334
+ and file.stem not in file_stems
335
+ ]
336
+ # candidates heave text-like suffix and no translation yet (no file in folder with target language code
337
+ click.echo(f"{len(translate_file_paths)} files to be processed")
338
+
339
+ for file in translate_file_paths:
340
+ if "~$" in file.name:
341
+ click.echo(f"Skipping {file}")
342
+ continue
343
+ click.echo(f"Processing {file}")
344
+ args = dict()
345
+ args['target_lang'] = target_language
346
+ if source_language != "AUTO":
347
+ args["source_lang"] = source_language
348
+ if prompt:
349
+ args["prompt"] = prompt
350
+ translate_it(file, translator, args)
351
+
352
+
353
+ # the `cli` command config
354
+ @cli.group("config", help="configuration")
355
+ def config():
356
+ pass
357
+
358
+
359
+ # the `config` create subcommand
360
+ @click.command("create", help="Create new configuration file")
361
+ def create():
362
+ msg = "Select folder to containing the sound files"
363
+ click.echo(msg)
364
+ # root = tk.Tk()
365
+ # root.focus_force()
366
+ # Cause the root window to disappear milliseconds after calling the filedialog.
367
+ # root.after(100, root.withdraw)
368
+ # tk.Tk().withdraw()
369
+ # hangs: mb.showinfo("msg","Select folder containing the sound files")
370
+ msgbox.alert(msg, "info")
371
+ # "title" only supported on linux ith wv ...
372
+ folder = askdirectory(
373
+ title="Select folder to monitor containing the sound files",
374
+ mustexist=True,
375
+ initialdir="~",
376
+ )
377
+ choices = ["tiny", "base", "small", "medium", "large", "turbo"]
378
+ # inx = ask_choice("Choose a model", choices)
379
+ # model = choices[inx]
380
+ model = Prompt.ask(
381
+ "Choose a model",
382
+ console=console,
383
+ choices=choices,
384
+ show_default=True,
385
+ default="large",
386
+ )
387
+ config_name = Prompt.ask(
388
+ "Enter a name for the configuration file",
389
+ show_default=True,
390
+ default="localwhisper.toml",
391
+ )
392
+ config_path = Path(config_name)
393
+ toml_path = config_path.with_suffix(".toml")
394
+ while toml_path.exists(): # current dir
395
+ result = get_config_from_toml(toml_path)
396
+ click.secho("Already exists...", fg="red")
397
+ show_config(result)
398
+ overwrite = Prompt.ask(
399
+ "Overwrite?", choices=["y", "n"], default="n", show_default=True
400
+ )
401
+ if overwrite == "y":
402
+ break
403
+ else:
404
+ return
405
+ # Prompt.ask("Enter model name")
406
+ save_config_to_toml(toml_path, folder, model)
407
+ click.echo(f"{toml_path} saved")
408
+
409
+
410
+ # the 'config' show subcommand
411
+ @click.command("show", help="Show current configuration file")
412
+ @click.pass_obj
413
+ def show(config):
414
+ click.echo(f"Config folder path: {config.folder}")
415
+ click.echo(f"Config model name: {config.model}")
416
+
417
+
418
+ # connect the subcommand to `config'
419
+ config.add_command(create)
420
+ config.add_command(show)
421
+
422
+ if __name__ == "__main__":
423
+ cli()
@@ -0,0 +1,80 @@
1
+ from typing import Union
2
+ from pathlib import Path
3
+ import click
4
+ from rich.prompt import Prompt
5
+ import toml
6
+ from result import is_ok, is_err, Ok, Err, Result # noqa: F401
7
+ from attrs import define
8
+ from rich.console import Console
9
+
10
+ console = Console(width=120, force_terminal=True)
11
+
12
+
13
+ @define
14
+ class Config:
15
+ folder: str
16
+ model: str
17
+ debug: bool = False
18
+
19
+
20
+ def save_config_to_toml(filepath,
21
+ folder: Union[str, Path] = "",
22
+ model_name: str = ""):
23
+ try:
24
+ # let's save a clean folder path, so we can use Path() when retrieving
25
+ data = {"folder": str(folder), "model": model_name}
26
+ with open(filepath, 'w') as toml_file:
27
+ # noinspection PyTypeChecker
28
+ toml.dump(data, toml_file)
29
+ except Exception as e:
30
+ click.secho(f"Error saving config to "
31
+ f"TOML file @ {filepath}: {e}", fg='red')
32
+
33
+
34
+ def get_config_from_toml(filepath) -> Result:
35
+ try:
36
+ with open(filepath, 'r') as toml_file:
37
+ data = toml.load(toml_file)
38
+ except FileNotFoundError:
39
+ return Err("TOML file not found.")
40
+ except toml.TomlDecodeError:
41
+ return Err("Error decoding TOML file.")
42
+ except Exception as e:
43
+ return Err(f"Unexpected error: {e}")
44
+ else:
45
+ config = Config(**data) # as data is flat, it's ok
46
+ return Ok(config)
47
+
48
+
49
+ def ask_choice(msg: str, choices) -> int:
50
+
51
+ # Print het keuzemenu
52
+ console.print(
53
+ f"[bold magenta]{msg}[/bold magenta]\n"
54
+ "[yellow]Kies een van de volgende opties:[/yellow]"
55
+ )
56
+ for i, choice in enumerate(choices, start=1):
57
+ console.print(f"{i}. {choice}")
58
+
59
+ # Vraag input van de gebruiker
60
+ user_input = Prompt.ask(
61
+ "Voer het nummer van je keuze in",
62
+ choices=[str(i) for i in range(1, len(choices) + 1)]
63
+ )
64
+
65
+ # Verwerk de keuze
66
+ chosen_option = choices[int(user_input) - 1] # Converteer input naar index
67
+ console.print(f"[green]Je hebt gekozen voor:[/green] {chosen_option}")
68
+
69
+ return chosen_option
70
+
71
+
72
+ def show_config(result: Result):
73
+ if is_err(result):
74
+ click.echo(f"Exiting due to {result.err}")
75
+ return False
76
+ config = result.ok_value
77
+ if config:
78
+ click.echo(f"Config folder path: {config.folder}")
79
+ click.echo(f"Config model name: {config.model}")
80
+ return True
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: TranscribeTools
3
+ Version: 0.5.5
4
+ Summary: Transcribe all soundfiles in a folder using Whisper
5
+ License-File: LICENSE
6
+ License-File: LICENSE-2.0.txt
7
+ Requires-Dist: attrs>=24.2.0
8
+ Requires-Dist: openai-whisper>=20240930
9
+ Requires-Dist: openai>=1.59.4
10
+ Requires-Dist: pymsgbox>=1.0.9
11
+ Requires-Dist: result>=0.17.0
12
+ Requires-Dist: rich-click>=1.8.5
13
+ Requires-Dist: soundfile>=0.13.0
14
+ Requires-Dist: tiutools>=0.4.1
15
+ Requires-Dist: toml>=0.10.2
16
+ Requires-Dist: transformers>=4.49.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # LocalWhisper
20
+
21
+ ## Introduction
22
+ TranscribeTools is an Python application which transcribes all
23
+ sound files in a configurable folder using a local Whisper model.
24
+ TranscribeTools contains an Python application LocalWhisper
25
+ which transcribes all sound files in a configurable folder using a local Whisper model.
26
+ You can choose which Whisper model is to be used
27
+
28
+ ## Details
29
+ - using Python 3.12.7, openai-whisper https://pypi.org/project/openai-whisper/ (current version 20240930)
30
+ does not support 3.13 yet.
31
+
32
+ ## License
33
+ This project is licensed under the Apache 2.0 License - see the [LICENSE file](LICENSE) for details.
34
+
35
+ ## Setup
36
+ We use uv for managing virtual environments and package installation. Follow these steps to set up the project:
37
+
38
+ ### On macOS:
39
+ #### Install uv
40
+ - First install brew if needed from https://github.com/Homebrew/brew/releases/latese
41
+
42
+ ### On Windows:
43
+ #### Download the setup script
44
+ We need to install `UV` a tool to install the Python environment and to
45
+ install the tool. There are a few possibilities
46
+
47
+ 1. Follow instructions at [the UV website](https://docs.astral.sh/uv/getting-started/installation/#__tabbed_1_2)
48
+
49
+ 2. Press {Windows button} then type or paste:.
50
+ ```powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"```
51
+
52
+ 3. Use `winget`
53
+ - Open the Windows Powershell: press {Windows} button and type or paste
54
+ ```Powershell
55
+ winget install --id=astral-sh.uv -e
56
+ ```
57
+
58
+ ### These scripts will:
59
+
60
+ Installs the `uv` tool. Check if `uv {enter}` works. [At the moment](https://github.com/astral-sh/uv/issues/10014) a reboot is needed on Windows.
61
+ Now we can install the tools.
62
+
63
+ ### Install tools
64
+
65
+ ```uv tool install transcribetools```
66
+
67
+ Install the (commandline) tools in this project. For now
68
+ it's only `transcribe_folder`.
69
+
70
+ ## Plans
71
+ - Make it a local service, running in the background
72
+ - Investigate options to let it run on a central computer, as a service
73
+ - Create Docker image
74
+ - Add speaker partitioning (see TranscribeWhisperX)
75
+ - Adjust models using PyTorch (more control)
76
+
77
+ ## Documentation about Whisper on the cloud and local
78
+ - [Courtesy of and Credits to OpenAI: Whisper.ai](https://github.com/openai/whisper/blob/main/README.md)
79
+ - [doc](https://pypi.org/project/openai-whisper/)
80
+ - [alternatief model transcribe and translate](https://huggingface.co/facebook/seamless-m4t-v2-large)
@@ -0,0 +1,13 @@
1
+ transcribetools/__init__.py,sha256=0cQb9ynDzYaDSNCTalMwK8u4BZajF_b8-9R59OQCHWY,159
2
+ transcribetools/commandline.py,sha256=JqsmXy7SZwQ_clZiU67Ixv8TE0ylHr6CyoeKFc5awKk,157
3
+ transcribetools/config.toml,sha256=gqbWdxviZn34UqAk1CzE-zRsP8j3j8KTal1o6nEdz1Q,146
4
+ transcribetools/local_whisper.py,sha256=pYkgYwLUlYZNJMUh3-5dO46OgRXRiVZKkiblCs4ESFo,6680
5
+ transcribetools/local_wisper_model.py,sha256=5EpGhQRnovvvlvQ9JrttxHd_bWUrq0fiQ29o1ITNYnU,2039
6
+ transcribetools/transcribe_folder.py,sha256=JZkXp0XAWDC7ohGypLeOcunL3z1idAj16mG0Di_jKok,13208
7
+ transcribetools/transcribe_folder_model.py,sha256=f33TjphqBeF4oMaBh92SPH_Q-v-tbQbpKez-7zku3Rg,2361
8
+ transcribetools-0.5.5.dist-info/METADATA,sha256=eV16OqI4kS6Iiy6EmRcZkOLfq6XL6LCkH9Q5GE93OSE,2875
9
+ transcribetools-0.5.5.dist-info/WHEEL,sha256=tkmg4JIqwd9H8mL30xA7crRmoStyCtGp0VWshokd1Jc,105
10
+ transcribetools-0.5.5.dist-info/entry_points.txt,sha256=gpsp8wfXw5oLExXuyXBP0BzEYxUBh4iGHiGLrp7aXug,75
11
+ transcribetools-0.5.5.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ transcribetools-0.5.5.dist-info/licenses/LICENSE-2.0.txt,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ transcribetools-0.5.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ transcribefolder = transcribetools.transcribe_folder:cli
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.