Skip to content

Instantly share code, notes, and snippets.

@tomowarkar
Created March 7, 2021 01:46
Show Gist options
  • Select an option

  • Save tomowarkar/ac2f5c6620595dfa1d3230713ec49d64 to your computer and use it in GitHub Desktop.

Select an option

Save tomowarkar/ac2f5c6620595dfa1d3230713ec49d64 to your computer and use it in GitHub Desktop.
url からファイルのダウンロード
import os
import tempfile
import ffmpeg
import requests
from tqdm import tqdm
def download(url, filename):
_, tmpfile = tempfile.mkstemp()
try:
_download(url, tmpfile)
except:
os.remove(tmpfile)
os.rename(tmpfile, filename)
def _download(url, filename, desc=""):
chunk_size = 1024
filesize = int(requests.head(url).headers["Content-Length"])
with requests.get(url, stream=True) as r, open(filename, "wb") as f, tqdm(
unit="B", total=filesize, unit_scale=True, unit_divisor=1024, desc=desc
) as progress:
for chunk in r.iter_content(chunk_size=chunk_size):
datasize = f.write(chunk)
progress.update(datasize)
def download2(video_url, audio_url, filename):
_, tmpvideo = tempfile.mkstemp(suffix=".m4s")
_, tmpaudio = tempfile.mkstemp(suffix=".m4s")
try:
print("[download] Destination:", tmpvideo)
_download(video_url, tmpvideo, "[download video]")
print("[download] Destination:", tmpaudio)
_download(audio_url, tmpaudio, "[download audio]")
ffmpeg.concat(ffmpeg.input(tmpvideo), ffmpeg.input(tmpaudio), v=1, a=1).output(
filename
).run()
except:
os.remove(tmpvideo)
os.remove(tmpaudio)
print("[error] download failed")
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment