Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added silence_level_analysis (sla) for easier deciding of silence level #25

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions unsilence/command_line/EntryPoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from unsilence.Unsilence import Unsilence
from unsilence.command_line.ChoiceDialog import choice_dialog
from unsilence.command_line.ParseArguments import parse_arguments
from unsilence.command_line.PrettyTimeEstimate import pretty_time_estimate
from unsilence.command_line.PrettyTimeEstimate import pretty_time_estimate, pretty_time_estimate_sla
from unsilence.command_line.TerminalSupport import repair_console


Expand All @@ -25,9 +25,10 @@ def main():
sys.exit(0)


def run():
def run(sla=False):
"""
Run the Console Interface for Unsilence
optional argument :sla: - True if the user wishes to rerun with sla on after finding output to be same as input.
:return: None
"""
sys.tracebacklimit = 0
Expand All @@ -38,7 +39,7 @@ def run():
if args.debug:
sys.tracebacklimit = 1000

if args.output_file.exists() and not args.non_interactive_mode:
if args.output_file.exists() and not args.non_interactive_mode and not sla: # Don't ask whether want to overwrite second time when ran with SLA.
if not choice_dialog(console, "File already exists. Overwrite?", default=False):
return

Expand Down Expand Up @@ -69,9 +70,41 @@ def run():
def update_task(current_task):
def handler(current_val, total):
progress.update(current_task, total=total, completed=current_val)

return handler

if sla: #If user wishes to rerun with SLA on
args.silence_level_analysis = "normal"
if args.silence_level_analysis:
argument_dict_for_sla = argument_dict_for_silence_detect.copy()
estimated_times = {}

sla_levels = {'low': range(-60, -35, 5), # -60 to -40
'normal': range(-45, -20, 5), # -45 to -25
'high': range(-35, -10, 5), # -35 to -15
'full': range(-60, -5, 5)} # -60 to -10

for silence_level in sla_levels[args.silence_level_analysis]:
progress.start()
sla_subtask = progress.add_task("SLA for silence level " + str(silence_level), total=1)
argument_dict_for_sla['silence_level'] = silence_level
continual.detect_silence(on_silence_detect_progress_update=update_task(sla_subtask), **argument_dict_for_sla)
estimated_times['silence_level_'+str(silence_level)] = continual.estimate_time(args.audible_speed, args.silent_speed)
progress.stop()
progress.remove_task(sla_subtask)

console.print(pretty_time_estimate_sla(estimated_times))
if not args.non_interactive_mode:
if not choice_dialog(console, "Silence level analysis finished. Continue with original silence level?", default=True):
while True:
try:
new_silence_level = float(console.input("Enter a new silence level value: "))
break
except ValueError:
console.print("Please enter a valid value (float)")
argument_dict_for_silence_detect['silence_level'] = new_silence_level

progress.start()
silence_detect_task = progress.add_task("Calculating Intervals...", total=1)

continual.detect_silence(
Expand All @@ -87,10 +120,14 @@ def handler(current_val, total):
estimated_time = continual.estimate_time(args.audible_speed, args.silent_speed)
console.print(pretty_time_estimate(estimated_time))

print()

if not args.non_interactive_mode:
if not choice_dialog(console, "Continue with these options?", default=True):
if estimated_time['delta']['all'][0] == 0 and estimated_time['delta']['audible'][0] == 0 and estimated_time['delta']['silent'][0] == 0:
console.print("There is no change with the current parameters.")
if choice_dialog(console, "Run silence level analysis (sla) to find silence levels? Press n to continue instead anyway.", default="True"):
run(sla=True)
return

elif not choice_dialog(console, "Continue with these options?", default=True):
return

progress.start()
Expand Down
11 changes: 11 additions & 0 deletions unsilence/command_line/ParseArguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ def number_bigger_than_zero(s):

return i

def sla_input(s):
"""
Only valid if the input string is one of the valid sla options - low, normal, high, full
:param s: Input string
:return: String if it is one of low, normal, high or full.
"""
if s not in ["low", "normal", "high", "full"]:
raise argparse.ArgumentTypeError("sla string must be one of low, normal, high or full.")
return s

def parse_arguments():
"""
Expand Down Expand Up @@ -88,5 +97,7 @@ def parse_arguments():

parser.add_argument("-d", "--debug", action="store_true",
help="Enable debug output (StackTrace)")
parser.add_argument("-sla", "--silence-level-analysis", type=sla_input, const="normal", nargs="?",
help="Helps to decide silence level, might take some time. Four options - low, normal, high, full.")

return parser.parse_args()
30 changes: 30 additions & 0 deletions unsilence/command_line/PrettyTimeEstimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,33 @@ def pretty_time_estimate(time_data: dict):
)

return table

def pretty_time_estimate_sla(time_data: dict):
"""
Printing the silent level analysis
Generates a rich.table.Table object from the time_data dict (from lib.Intervals.TimeCalculations.calculate_time)
:param time_data: time_data nested dict with silence levels
:return: rich.table.Table object
"""
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Silence Levels")
table.add_column("Detected Silence")
table.add_column("Combined_Before")
table.add_column("Combined_After")

for key in time_data.keys():
reorderer_time_data = {"all": {}, "audible": {}, "silent": {}}
for column, row_with_values in time_data[key].items():
for row, values in row_with_values.items():
time_delta = format_timedelta(round(values[0]))
reorderer_time_data[row][column] = f"{time_delta} ([cyan]{round(values[1] * 100, 1)}%[/cyan])"
table.add_row(
key.split('_')[-1],
reorderer_time_data["silent"]["before"],
reorderer_time_data["all"]["before"],
reorderer_time_data["all"]["after"]
)
return table