I'm not trying to download the whole video, just 5 seconds of a video. I tried following this guide. However, this is for in line command and I'm trying to do this with python code. So far I've managed to extract all the required information using youtube-dl. The problem I'm having now is using ffmpeg to output the video with the given parameters, but it's saying it cannot find the file specified.
This is what I have so far:
import youtube_dl
import datetime
import ffmpeg
def getInfo():
link='https://youtu.be/nda20uSjQUI?t=11981'
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})
#This exctracts all the information of the link
with ydl:
result = ydl.extract_info(
link,
download=False
)
#Grabs the duration of the video
duration_info = result.get('duration')
#Grabs the url to the actual video file
url = str(result).split("'url':",1)[1].split(', ')[0]
#YouTube(link).streams.first().download('D:/Downloads')
#Determines the start time based on how the link is formatted
#They can be in three possible formats
if 't=' in link:
if link.endswith('s'):
time_seconds = link.split('t=', 1)[1].strip('s')
else:
time_seconds = link.split('t=', 1)[1]
else:
time_seconds = '0'
#Converts the time into an HH:MM:ss format
#We only want 5 seconds of video, which is what timestamp_end does
timestamp_start = str(datetime.timedelta(seconds=int(time_seconds)))
timestamp_end = str(datetime.timedelta(seconds=int(time_seconds)+5))
video_length = str(datetime.timedelta(seconds=int(duration_info)))
#If the segment we want is less than 5 seconds, such as towards the end of the video,
#then the end will be the end of the actual video
if timestamp_end > video_length:
timestamp_end = video_length
#Returns a list of [url, start, end]
return url ,timestamp_start,timestamp_end
def download_video(result):
#Checks to see if there's a valid argument
if result is None:
return 'Error: no url found'
else:
file_input = ffmpeg.input(result[0])
out = ffmpeg.concat(file_input.trim(start_frame=result[1],end_frame=result[2])).output('test1.mp4').run()
return out
download_video(result=getInfo())
And this is the error I'm getting:
Traceback (most recent call last):
File "C:/Users/Anonymous/PycharmProjects/untitled/test.py", line 53, in <module>
download_video(result=getInfo())
File "C:/Users/Anonymous/PycharmProjects/untitled/test.py", line 50, in download_video
out = ffmpeg.concat(file_input.trim(start_frame=result[1],end_frame=result[2])).output('test1.mp4').run()
File "C:\Users\Anonymous\PycharmProjects\untitled3\venv\lib\site-packages\ffmpeg\_run.py", line 320, in run
overwrite_output=overwrite_output,
File "C:\Users\Anonymous\PycharmProjects\untitled3\venv\lib\site-packages\ffmpeg\_run.py", line 285, in run_async
args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\Lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\Lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
Process finished with exit code 1
Related
I tried to read file that I give with absolute path.
When I run my code first that I see is this message:
D:\prog\datascience\anaconda\lib\site-packages\pydub\utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
I tried this:
PATH_TO_FFMPEG = 'D:\\prog\\ffmpeg-win-2.2.2\\ffmpeg.exe'
pydub.AudioSegment.converter = r'D:\\prog\\ffmpeg-win-2.2.2\\ffmpeg.exe'
And I separately installed ffmpeg with pip. But it didn't help.
When I try this:
raw_sound = pydub.AudioSegment.from_mp3(file=track_path)
where track_path is correct absolute path generated automatically.
So I got this this error:
Traceback (most recent call last):
File "D:\prog\PyCharm Community Edition 2020.2.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1448, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "D:\prog\PyCharm Community Edition 2020.2.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "D:/testtask2/test_task/testtask/get_mffc.py", line 165, in <module>
slice_all_in_a_dir('May 27 2020 LNC/Hydrophone 1/raw_records')
File "D:/testtask2/test_task/testtask/get_mffc.py", line 70, in slice_all_in_a_dir
slice_samples(track_path= [file],
File "D:/testtask2/test_task/testtask/get_mffc.py", line 48, in slice_samples
raw_sound = pydub.AudioSegment.from_mp3(file=track_path)
File "D:\prog\datascience\anaconda\lib\site-packages\pydub\audio_segment.py", line 738, in from_mp3
return cls.from_file(file, 'mp3', parameters=parameters)
File "D:\prog\datascience\anaconda\lib\site-packages\pydub\audio_segment.py", line 680, in from_file
stdin_data = file.read()
AttributeError: 'list' object has no attribute 'read'
python-BaseException
Full code when I use it:
def slice_samples(track_path: list, save_path: str,
sample_folder_name: str, interval: float, given_format, name: str = "part", export_format = 'wav'):
"""
This metod slice given track to parts.
:param track_path: str, a path to the track you want to slice
:param save_path: str, a path to folder, where you want save sliced tracks
:param sample_folder_name: str, you don't need to create a folder for sliced tracks,
you can just write the name of the folder in this argument where you want to save tracks
:param interval: float, measure in seconds, the length of sliced tracks
:param name: str, name of sliced tacks
:param given_format: str, I strongly recommend use .wav format initially, when you record sounds
:return: folder with sliced tracks
"""
# it cuts a file in mp3 or wav formats (wav recommended)
interval_secs = interval * 10 ** 3
raw_sound = None
if given_format == "WAV":
raw_sound = pydub.AudioSegment.from_wav(file=track_path)
elif given_format == "MP3":
raw_sound = pydub.AudioSegment.from_mp3(file=track_path)
else:
raise Exception("It's temporarily unsupported given_format: " + given_format)
start = 0
end = interval_secs
i = 0
while end < len(raw_sound):
save_to = save_path + sample_folder_name + "/" + name + str(i)
part = raw_sound[start:end]
part.export(save_to, format=export_format)
i += 1
start += interval_secs
end += interval_secs
return save_path + sample_folder_name
def slice_all_in_a_dir(tracks_folder: str):
files = os.listdir(tracks_folder)
for file in files:
folder_name = file.split('.')
f_name = folder_name[0]
file = tracks_folder+'/'+file
file = os.path.abspath(file)
slice_samples(track_path= [file],
save_path= PATH_FOR_SLICED,
sample_folder_name= f_name,
interval=5,
given_format=folder_name[1])
if __name__ == "__main__":
slice_all_in_a_dir('May 27 2020 LNC/Hydrophone 1/raw_records')
can you please share the code which you are using , It will be helpful to find the exact issue.
AttributeError: 'list' object has no attribute 'read'
Also the error suggests that file is being treated as a list and not as file in the below code
stdin_data = file.read()
Hope I have given a solution.
I am on a project that trims video at specific time ,then converts it to an audio file and save it.
But the problem is i cannot get every Newly created audio file with a specific name that is stored inside a .txt file
Here's the Code
from moviepy.editor import *
import shutil
s= open("begin.txt") #Starting time
lines1 = s.readlines()
e = open("end.txt") #End Time
lines2 = e.readlines()
t = open("title.txt") #The text file which contain the file name
lines3 = t.readlines()
print("Starting...")
for x in range(1776): #Iam triming the video files to 1777 parts
st=lines1[x]
en=lines2[x]
t=lines3[x]
print("Start Time: "+st)
print("End Time: "+en)
video = VideoFileClip("J:\Movie\SM.mp4").subclip(st, en)
video.audio.write_audiofile("J:\Movie\ audio.mp3")
shutil.move("J:\Movie\ audio.mp3","J:\Movie\Data\ "+t+".mp3")
I have tried using both shutil.move and os.rename but both produce the same Error
Here's the Output:
Starting...
Start Time: 39.33
End Time: 41.958
MoviePy - Writing audio in J:\Movie\ audio.mp3
Traceback (most recent call last):
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 563, in move
os.rename(src, real_dst)
OSError: [WinError 123] The filename, directory name, or volume label syntax
is incorrect: 'J:\\Marvel\\ audio.mp3' -> 'J:\\Marvel\\Data\\ Things are
never
gonna bethe same now\n.mp3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/CRPSM/PycharmProjects/AC#/venv/fdsh.py", line 27, in <module>
shutil.move("J:\Marvel\ audio.mp3","J:\Marvel\Data\ "+t+".mp3")
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 577, in move
copy_function(src, real_dst)
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 263, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 121, in copyfile
with open(dst, 'wb') as fdst:
OSError: [Errno 22] Invalid argument: 'J:\\Marvel\\Data\\ Things are never
gonna bethe same now\n.mp3'
MoviePy - Done.
Process finished with exit code 1
1: You have an indentation error for the for-loop.
2: You should remove the '\n', which stands for newline, from each file name in you list:
from moviepy.editor import *
import shutil
s= open("begin.txt") #Starting time
lines1 = [l.strip() for l in s.readlines()]
e = open("end.txt") #End Time
lines2 = [l.strip() for l in e.readlines()]
t = open("title.txt") #The text file which contain the file name
lines3 = [l.strip() for l in t.readlines()]
print("Starting...")
for x in range(1776): #Iam triming the video files to 1777 parts
st=lines1[x]
en=lines2[x]
t=lines3[x]
print("Start Time: "+st)
print("End Time: "+en)
video = VideoFileClip("J:\Movie\SM.mp4").subclip(st, en)
video.audio.write_audiofile("J:\Movie\ audio.mp3")
shutil.move("J:\Movie\ audio.mp3","J:\Movie\Data\ "+t+".mp3")
I use the Pillow lib to create thumbnails. I have to create a lot of them, actually more than 10.000
The program works fine, but after processing round about 1.500, I get the following error:
Traceback (most recent call last):
File "thumb.py", line 15, in <module>
im = Image.open('/Users/Marcel/images/07032017/' + infile)
File "/Users/Marcel/product-/PIL/Image.py", line 2339, in open
im = _open_core(fp, filename, prefix)
File "/Users/Marcel/product-/PIL/Image.py", line 2329, in _open_core
im = factory(fp, filename)
File "/Users/Marcel/product-/PIL/ImageFile.py", line 97, in __init__
self._open()
File "/Users/Marcel/product-/PIL/PngImagePlugin.py", line 538, in _open
s = self.png.call(cid, pos, length)
File "/Users/Marcel/product-/PIL/PngImagePlugin.py", line 136, in call
return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length)
File "/Users/Marcel/product-/PIL/PngImagePlugin.py", line 319, in chunk_iCCP
icc_profile = _safe_zlib_decompress(s[i+2:])
File "/Users/Marcel/product-/PIL/PngImagePlugin.py", line 90, in _safe_zlib_decompress
raise ValueError("Decompressed Data Too Large")
ValueError: Decompressed Data Too Large
My program is very straight forward:
import os, sys
import PIL
from PIL import Image
size = 235, 210
reviewedProductsList = open('products.txt', 'r')
reviewedProducts = reviewedProductsList.readlines()
t = map(lambda s: s.strip(), reviewedProducts)
print "Thumbs to create: '%s'" % len(reviewedProducts)
for infile in t:
outfile = infile
try:
im = Image.open('/Users/Marcel/images/07032017/' + infile)
im.thumbnail(size, Image.ANTIALIAS)
print "thumb created"
im.save('/Users/Marcel/product-/thumbs/' + outfile, "JPEG")
except IOError, e:
print "cannot create thumbnail for '%s'" % infile
print "error: '%s'" % e
I am performing this operation locally on my MacBook Pro.
This is to protect against a potential DoS attack on servers running Pillow caused by decompression bombs. It occurs when a decompressed image is found to have too large metadata. See http://pillow.readthedocs.io/en/4.0.x/handbook/image-file-formats.html?highlight=decompression#png
Here's the CVE report: https:// www.cvedetails.com/cve/CVE-2014-9601/
From a recent issue:
If you set ImageFile.LOAD_TRUNCATED_IMAGES to true, it will suppress
the error (but still not read the large metadata). Alternately, you can
change set the values here: https://github.com/python-pillow/Pillow/ blob/master/PIL/PngImagePlugin.py#L74
https://github.com/python-pillow/Pillow/issues/2445
following code should help you in setting what accepted answer says.
from PIL import PngImagePlugin
LARGE_ENOUGH_NUMBER = 100
PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2)
It's not documented how to set this value. I hope people find this useful.
I have just downloaded instabot but when i tried to execute it i saw some errors, this is the main module("example.py"),there is source code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
sys.path.append(os.path.join(sys.path[0],'src'))
from instabot import InstaBot
from check_status import check_status
from feed_scanner import feed_scanner
from unfollow_protocol import unfollow_protocol
from follow_protocol import follow_protocol
import time
bot = InstaBot(login="username", password="password",
like_per_day=1000,
comments_per_day=0,
tag_list=['follow4follow', 'f4f', 'cute'],
tag_blacklist=['rain', 'thunderstorm'],
user_blacklist={},
max_like_for_one_tag=50,
follow_per_day=300,
follow_time=1*60,
unfollow_per_day=300,
unfollow_break_min=15,
unfollow_break_max=30,
log_mod=0,
proxy='',
# Use unwanted username list to block users which have username contains one of this string
## Doesn't have to match entirely example: mozart will be blocked because it contains *art
### freefollowers will be blocked because it contains free
unwanted_username_list=['second','stuff','art','project','love','life','food','blog','free','keren','photo','graphy','indo',
'travel','art','shop','store','sex','toko','jual','online','murah','jam','kaos','case','baju','fashion',
'corp','tas','butik','grosir','karpet','sosis','salon','skin','care','cloth','tech','rental',
'kamera','beauty','express','kredit','collection','impor','preloved','follow','follower','gain',
'.id','_id','bags'])
while True:
#print("# MODE 0 = ORIGINAL MODE BY LEVPASHA")
#print("## MODE 1 = MODIFIED MODE BY KEMONG")
#print("### MODE 2 = ORIGINAL MODE + UNFOLLOW WHO DON'T FOLLOW BACK")
#print("#### MODE 3 = MODIFIED MODE : UNFOLLOW PEOPLE WHO DON'T FOLLOW BACK BASED ON RECENT FEED ONLY")
#print("##### MODE 4 = MODIFIED MODE : FOLLOW PEOPLE BASED ON RECENT FEED ONLY")
#print("###### MODE 5 = MODIFIED MODE : JUST UNFOLLOW EVERYBODY, EITHER YOUR FOLLOWER OR NOT")
################################
## WARNING ###
################################
# DON'T USE MODE 5 FOR A LONG PERIOD. YOU RISK YOUR ACCOUNT FROM GETTING BANNED
## USE MODE 5 IN BURST MODE, USE IT TO UNFOLLOW PEOPLE AS MANY AS YOU WANT IN SHORT TIME PERIOD
mode = 0
#print("You choose mode : %i" %(mode))
#print("CTRL + C to cancel this operation or wait 30 seconds to start")
#time.sleep(30)
if mode == 0 :
bot.new_auto_mod()
elif mode == 1 :
check_status(bot)
while bot.self_following - bot.self_follower > 200:
unfollow_protocol(bot)
time.sleep(10*60)
check_status(bot)
while bot.self_following - bot.self_follower < 400:
while len(bot.user_info_list) <50 :
feed_scanner(bot)
time.sleep(5*60)
follow_protocol(bot)
time.sleep(10*60)
check_status(bot)
elif mode == 2 :
bot.bot_mode = 1
bot.new_auto_mod()
elif mode == 3 :
unfollow_protocol(bot)
time.sleep(10*60)
elif mode == 4 :
feed_scanner(bot)
time.sleep(60)
follow_protocol(bot)
time.sleep(10*60)
elif mode == 5 :
bot.bot_mode=2
unfollow_protocol(bot)
else :
print ("Wrong mode!")
when i launched it i saw those errors :
Trying to login as username...
Traceback (most recent call last):
File "example.py", line 35, in <module>
'.id','_id','bags'])
File "/home/mohand/Desktop/instabot.py-master/src/instabot.py", line 185, in __init__
self.login()
File "/home/mohand/Desktop/instabot.py-master/src/instabot.py", line 224, in login
r = self.s.get(self.url)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/sessions.py", line 501, in get
return self.request('GET', url, **kwargs)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/sessions.py", line 488, in request
resp = self.send(prep, **send_kwargs)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/sessions.py", line 609, in send
r = adapter.send(request, **kwargs)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/adapters.py", line 423, in send
timeout=timeout
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 594, in urlopen
chunked=chunked)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 350, in _make_request
self._validate_conn(conn)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 835, in _validate_conn
conn.connect()
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connection.py", line 330, in connect
cert = self.sock.getpeercert()
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 324, in getpeercert
'subjectAltName': get_subj_alt_name(x509)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 171, in get_subj_alt_name
ext = cert.extensions.get_extension_for_class(
AttributeError: 'Extensions' object has no attribute 'get_extension_for_class'
I'm using python 3.5 please i need help :)
You might want to upgrade your version of cryptography. Check here for details on this issue
Try This:
sudo pip install cryptography --upgrade
def morse_audio( item ):
from pyglet import media
import pyglet
import time
import glob
import os
import wave
from contextlib import closing
files = []
audios = []
for file in glob.glob('C:\\Users\\MQ\'s Virual World\\Downloads\\Morse\\*.wav'):
ass = str(os.path.join('C:\\Users\MQ\'s Virual World\\Downloads\\Morse', file))
print (ass)
files.append(ass)
#audio = media.load(files[1])
#audio.play()
#print (len(files))
one = list(item)
str_list = [x.strip(' ') for x in one]
str_list = [x.strip('/') for x in str_list]
for s in str_list[0]:
if s != "-" and s != ".":
list(item)
for letter in item:
for i in range(0, 51):
if letter == " ":
time.sleep(1.5)
audios.append("noise3.wav")
break
if letter != letterlst[i] and letter != letterlst[i].lower():
continue
else:
print (files[i])
audio = media.load(files[i])
audio.play()
audios.append(files[i])
audios.append("noise2.wav")
time.sleep(1)
else:
lst = item.split()
print (' '.join(lst))
for code in lst:
for i in range(0, 51):
if code == "/":
time.sleep(1.5)
audios.append("noise3.wav")
break
if code != morse[i]:
continue
else:
print (files[i])
audio = media.load(files[i])
audio.play()
audios.append(files[i])
audios.append("noise2.wav")
time.sleep(1)
break
outfile = "sounds.wav"
data= []
for file in audios:
w = wave.open(file, 'rb')
lol = w.getparams()
print (lol)
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
with closing(wave.open(outfile, 'wb')) as output:
# find sample rate from first file
with closing(wave.open(audios[0])) as w:
output.setparams(w.getparams())
# write each file to output
for audioo in audios:
with closing(wave.open(audioo)) as w:
output.writeframes(w.readframes(w.getnframes()))()))
So this code previously worked but I wanted to use different file types other then .wav files but because that worked so poorly I went back to .wav. These are different .wav files but the ones that worked before get the same error message. Which is:
Traceback (most recent call last):
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\morsecode.py", line 187, in <module>
morse_audio("0123456789ÁÄ#&':,$=!-().+?;/_")
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\morsecode.py", line 96, in morse_audio
audio.play()
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 473, in play
player.play()
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 1012, in play
self._set_playing(True)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 993, in _set_playing
self._create_audio_player()
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 1083, in _create_audio_player
self._audio_player = audio_driver.create_audio_player(group, self)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\drivers\directsound\__init__.py", line 502, in create_audio_player
return DirectSoundAudioPlayer(source_group, player)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\drivers\directsound\__init__.py", line 184, in __init__
None)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\com.py", line 125, in <lambda>
self.method.get_field()(self.i, self.name)(obj, *args)
File "_ctypes/callproc.c", line 920, in GetResult
OSError: [WinError -2147024809] The parameter is incorrect
I've tried .wav files that used to work. It works when I use a .ogg file. Also works with mp3s. Seems only .wav files are giving it issues. Very suddenly and randomly.