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

fix PermissionError in Windows #16

Open
wants to merge 2 commits into
base: fix/windows_cutting
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
9 changes: 5 additions & 4 deletions silence_cutter.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ def ffmpeg_run (file, videoFilter, audioFilter, outfile):
logging.debug(f"ffmpeg_run ()")

# prepare filter files
vFile = tempfile.NamedTemporaryFile (mode="w", encoding="UTF-8", prefix="silence_video")
aFile = tempfile.NamedTemporaryFile (mode="w", encoding="UTF-8", prefix="silence_audio")
vFile = tempfile.NamedTemporaryFile (mode="w", encoding="UTF-8", delete=False, prefix="silence_video")
aFile = tempfile.NamedTemporaryFile (mode="w", encoding="UTF-8", delete=False, prefix="silence_audio")

videoFilter_file = vFile.name #"/tmp/videoFilter" # TODO: replace with tempfile
audioFilter_file = aFile.name #"/tmp/audioFilter" # TODO: replace with tempfile
Expand All @@ -124,11 +124,12 @@ def ffmpeg_run (file, videoFilter, audioFilter, outfile):
"-filter_script:v",videoFilter_file,
"-filter_script:a",audioFilter_file,
outfile]
subprocess.run (command)
subprocess.run (command, check=True)

vFile.close()
aFile.close()

os.remove(videoFilter_file)
os.remove(audioFilter_file)


def cut_silences(infile, outfile, dB = -35):
Expand Down
212 changes: 212 additions & 0 deletions silence_cutter_padding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
# Created by DarkTrick - 4fb5f723849d32782e723c34bfd132e442d378d7

import subprocess
import tempfile
import sys
import os
import logging
import re

# ===========================
# ==== Configure logging ====
# ===========================
log_level = logging.ERROR
log_filename = 'silence_cutter.log'
logger = logging.getLogger('')
logger.setLevel(log_level)
log_handler = logging.FileHandler(log_filename, delay=True)
logger.addHandler(log_handler)


def findSilences(filename, dB = -35, padding = 0.025):
"""
returns a list:
even elements (0,2,4, ...) denote silence start time
uneven elements (1,3,5, ...) denote silence end time

"""
logging.debug(f"findSilences ()")
logging.debug(f" - filename = {filename}")
logging.debug(f" - dB = {dB}")
logging.debug(f" - padding = {padding}")

command = ["ffmpeg","-i",filename,
"-af","silencedetect=n=" + str (dB) + "dB:d=1",
"-f","null","-"]
output = subprocess.run (command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
s = str(output)
lines = s.split("\\n")
time_list = []
logging.debug(" lines: ```\n" + "\n".join(lines) + "```\n\n")

for line in lines:
if ("silencedetect" in line):
words = line.split(" ")
logging.debug(" words: " + str(words))
for i in range (len(words)):
if ("silence_start" in words[i]):
clean_time = re.sub(r'[^\d.]+', '', words[i+1])
time_list.append (float(clean_time) + padding)
if "silence_end" in words[i]:
clean_time = re.sub(r'[^\d.]+', '', words[i+1])
time_list.append (float (clean_time) - padding)
silence_section_list = list (zip(*[iter(time_list)]*2))

#return silence_section_list
return time_list


def getVideoDuration(filename:str) -> float:
logging.debug(f"getVideoDuration ()")
logging.debug(f" - filename = {filename}")

command = ["ffprobe","-i",filename,"-v","quiet",
"-show_entries","format=duration","-hide_banner",
"-of","default=noprint_wrappers=1:nokey=1"]

output = subprocess.run (command, stdout=subprocess.PIPE)
s = str(output.stdout, "UTF-8")
return float (s)

def getSectionsOfNewVideo (silences, duration):
"""Returns timings for parts, where the video should be kept"""
return [0.0] + silences + [duration]


def ffmpeg_filter_getSegmentFilter(videoSectionTimings):
ret = ""
for i in range (int (len(videoSectionTimings)/2)):
start = videoSectionTimings[2*i]
end = videoSectionTimings[2*i+1]
ret += "between(t," + str(start) + "," + str(end) + ")+"
# cut away last "+"
ret = ret[:-1]
return ret

def getFileContent_videoFilter(videoSectionTimings):
ret = "select='"
ret += ffmpeg_filter_getSegmentFilter (videoSectionTimings)
ret += "', setpts=N/FRAME_RATE/TB"
return ret

def getFileContent_audioFilter(videoSectionTimings):
ret = "aselect='"
ret += ffmpeg_filter_getSegmentFilter (videoSectionTimings)
ret += "', asetpts=N/SR/TB"
return ret

def writeFile (filename, content):
logging.debug(f"writeFile ()")
logging.debug(f" - filename = {filename}")

with open (filename, "w") as file:
file.write (str(content))


def ffmpeg_run (file, videoFilter, audioFilter, outfile):
logging.debug(f"ffmpeg_run ()")

# prepare filter files
vFile = tempfile.NamedTemporaryFile (mode="w", encoding="UTF-8", delete=False, prefix="silence_video")
aFile = tempfile.NamedTemporaryFile (mode="w", encoding="UTF-8", delete=False, prefix="silence_audio")

videoFilter_file = vFile.name #"/tmp/videoFilter" # TODO: replace with tempfile
audioFilter_file = aFile.name #"/tmp/audioFilter" # TODO: replace with tempfile
writeFile (videoFilter_file, videoFilter)
writeFile (audioFilter_file, audioFilter)

command = ["ffmpeg","-i",file,
"-filter_script:v",videoFilter_file,
"-filter_script:a",audioFilter_file,
outfile]
subprocess.run (command, check=True)

vFile.close()
aFile.close()
os.remove(videoFilter_file)
os.remove(audioFilter_file)



def cut_silences(infile, outfile, dB = -35, padding = 0.025):
logging.debug(f"cut_silences ()")
logging.debug(f" - infile = {infile}")
logging.debug(f" - outfile = {outfile}")
logging.debug(f" - dB = {dB}")
logging.debug(f" - padding = {padding}")

print ("detecting silences")
silences = findSilences (infile,dB,padding)
duration = getVideoDuration (infile)
videoSegments = getSectionsOfNewVideo (silences, duration)

videoFilter = getFileContent_videoFilter (videoSegments)
audioFilter = getFileContent_audioFilter (videoSegments)

print ("create new video")
ffmpeg_run (infile, videoFilter, audioFilter, outfile)

def printHelp():
print ("Usage:")
print (" silence_cutter.py [infile] [optional: outfile] [optional: dB] [optional: padding]")
print (" ")
print (" [outfile]")
print (" Default: [infile]_cut")
print (" ")
print (" [dB]")
print (" Default: -30")
print (" A suitable value might be around -50 to -35.")
print (" The lower the more volume will be defined das 'silent'")
print (" -30: Cut Mouse clicks and mouse movent; cuts are very recognizable.")
print (" -35: Cut inhaling breath before speaking; cuts are quite recognizable.")
print (" -40: Cuts are almost not recognizable.")
print (" -50: Cuts are almost not recognizable.")
print (" Cuts nothing, if there is background noise.")
print (" ")
print (" [padding]")
print (" Default: 0.025")
print (" How much time to pad around each cut")
print (" ")
print ("")
print ("Dependencies:")
print (" ffmpeg")
print (" ffprobe")

def main():
logging.debug(f"main ()")
args = sys.argv[1:]
if (len(args) < 1):
printHelp()
return

if (args[0] == "--help"):
printHelp()
return

infile = args[0]

if (not os.path.isfile (infile)):
print ("ERROR: The infile could not be found:\n" + infile)
return

# set default values for optionl arguments
tmp = os.path.splitext (infile)
outfile = tmp[0] + "_cut" + tmp[1]
dB = -30
padding = 0.025

if (len(args) >= 2):
outfile = args[1]

if (len(args) >= 3):
dB = int(args[2])

if (len(args) >= 4):
padding = float(args[3])


cut_silences (infile, outfile, dB, padding)


if __name__ == "__main__":
main()