Exemplo n.º 1
0
    def upload(self, pic_info):
        try:
            api = InstagramAPI(self.account, self.password)
            if (api.login()):
                startCount = len(api.getTotalSelfUserFeed(self.account))
                photo_path = pic_info['Path']
                caption = self.genCaption(pic_info["Title"],
                                          pic_info["Subreddit"])
                if caption is None:
                    caption = self.titles[r.randint(
                        0,
                        len(self.titles) - 1
                    )] + "#lol #lmao #funny #rofl #meme #error #404 #human #notabot"

                if pic_info['FileFormat'] not in ['jpg', 'png']:
                    clip = VideoFileClip(photo_path)
                    clip.save_frame("images/thumbnail.jpg")
                    api.uploadVideo(photo_path,
                                    "images/thumbnail.jpg",
                                    caption=caption)
                    statusCode = api.LastResponse.status_code
                    if statusCode == 500:
                        print("Retrying to upload video in 10s")
                        time.sleep(10)
                        api.uploadVideo(photo_path,
                                        "images/thumbnail.jpg",
                                        caption=caption)
                else:
                    api.uploadPhoto(photo=photo_path, caption=caption)

                if len(api.getTotalSelfUserFeed(
                        self.account)) - startCount >= 1:
                    iID = self.db.insert("Instagram", [caption, self.account])
                    self.db.insert("Posted", [pic_info["ID"], iID])
                    print("Uploaded Post!")
                    return True
                else:
                    print("Didn't upload post :(")
                    self.db.update("Reddit", {"Path": "null"},
                                   "Reddit.ID == {0}".format(pic_info["ID"]))
                    return False
            else:
                print("Can't login!")
                return False
        except Exception as e:
            print("ERROR WHILE UPLOADING: ", e)
            self.db.update("Reddit", {"Path": "null"},
                           "Reddit.ID == {0}".format(pic_info["ID"]))
            return False
Exemplo n.º 2
0
def test_save_frame():
    clip = VideoFileClip("media/big_buck_bunny_432_433.webm")
    location = os.path.join(TMP_DIR, "save_frame.png")
    clip.save_frame(location, t=0.5)
    assert os.path.isfile(location)
    close_all_clips(locals())
#    if os.path.isfile(voutput2):
#        os.remove(voutput2)   
#    if os.path.isfile(voutput3):
#        os.remove(voutput3) 
#    if os.path.isfile(voutput4):
#        os.remove(voutput4)      
##    video_clip = VideoFileClip(video)
##    processed_clip = video_clip.fl_image(frame_processor)
##    %time    processed_clip.write_videofile(voutput, audio=False)
#    clip1 = VideoFileClip(video1).subclip(7,11)
#    clip1.write_videofile(voutput1, audio=False)
#    clip2 = VideoFileClip(video1).subclip(22,32)
#    clip2.write_videofile(voutput2, audio=False)    
#    clip3 = VideoFileClip(video1).subclip(35,47)
#    clip3.write_videofile(voutput3, audio=False) 
#    
#    clip4 = VideoFileClip(video2).subclip(0,7)
#    clip4.write_videofile(voutput4, audio=False)
############
#lets' generate some images to generalize image thresholding
vid1=video1
video_clip1= VideoFileClip(vid1)
video_clip1.save_frame('./project_video_30s.jpg', t='00:00:30')

vid2 = video2
video_clip2= VideoFileClip(vid2)
video_clip2.save_frame('./challenge_video_3s.jpg', t='00:00:03')

vid3 = video3
video_clip3= VideoFileClip(vid3)
video_clip3.save_frame('./harder_challenge_video_3s.jpg', t='00:00:03')
Exemplo n.º 4
0
def prepare_video(vid,
                  thumbnail_frame_ts=0.0,
                  max_size=(1080, 1350),
                  aspect_ratios=(4.0 / 5.0, 90.0 / 47.0),
                  max_duration=60.0,
                  save_path=None,
                  skip_reencoding=False,
                  **kwargs):
    """
    Prepares a video file for posting.
    Defaults for size and aspect ratio from https://help.instagram.com/1469029763400082

    :param vid: file path
    :param thumbnail_frame_ts: the frame of clip corresponding to time t (in seconds) to be used as the thumbnail
    :param max_size: tuple of (max_width,  max_height)
    :param aspect_ratios: single float value or tuple of (min_ratio, max_ratio)
    :param max_duration: maximum video duration in seconds
    :param save_path: optional output video file path
    :param skip_reencoding: if set to True, the file will not be re-encoded
        if there are no modifications required. Default: False.
    :param kwargs:
         - **min_size**: tuple of (min_width,  min_height)
         - **progress_bar**: bool flag to show/hide progress bar
         - **save_only**: bool flag to return only the path to the saved video file. Requires save_path be set.
         - **preset**: Sets the time that FFMPEG will spend optimizing the compression.
         Choices are: ultrafast, superfast, veryfast, faster, fast, medium,
         slow, slower, veryslow, placebo. Note that this does not impact
         the quality of the video, only the size of the video file. So
         choose ultrafast when you are in a hurry and file size does not matter.
    :return:
    """
    from moviepy.video.io.VideoFileClip import VideoFileClip
    from moviepy.video.fx.all import resize, crop

    min_size = kwargs.pop('min_size', (612, 320))
    progress_bar = True if kwargs.pop('progress_bar', None) else False
    save_only = kwargs.pop('save_only', False)
    preset = kwargs.pop('preset', 'medium')
    if save_only and not save_path:
        raise ValueError('"save_path" cannot be empty.')
    if save_path:
        if not save_path.lower().endswith('.mp4'):
            raise ValueError('You must specify a .mp4 save path')

    vid_is_modified = False  # flag to track if re-encoding can be skipped

    temp_video_file = tempfile.NamedTemporaryFile(prefix='ipae_',
                                                  suffix='.mp4',
                                                  delete=False)

    if is_remote(vid):
        # Download remote file
        res = requests.get(vid)
        temp_video_file.write(res.content)
        video_src_filename = temp_video_file.name
    else:
        shutil.copyfile(vid, temp_video_file.name)
        video_src_filename = vid

    vidclip = VideoFileClip(temp_video_file.name)

    if vidclip.duration < 3 * 1.0:
        raise ValueError('Duration is too short')

    if vidclip.duration > max_duration * 1.0:
        vidclip = vidclip.subclip(0, max_duration)
        vid_is_modified = True

    if thumbnail_frame_ts > vidclip.duration:
        raise ValueError('Invalid thumbnail frame')

    if aspect_ratios:
        crop_box = calc_crop(aspect_ratios, vidclip.size)
        if crop_box:
            vidclip = crop(vidclip,
                           x1=crop_box[0],
                           y1=crop_box[1],
                           x2=crop_box[2],
                           y2=crop_box[3])
            vid_is_modified = True

    if max_size or min_size:
        new_size = calc_resize(max_size, vidclip.size, min_size=min_size)
        if new_size:
            vidclip = resize(vidclip, newsize=new_size)
            vid_is_modified = True

    temp_vid_output_file = tempfile.NamedTemporaryFile(prefix='ipae_',
                                                       suffix='.mp4',
                                                       delete=False)
    if vid_is_modified or not skip_reencoding:
        # write out
        vidclip.write_videofile(temp_vid_output_file.name,
                                codec='libx264',
                                audio=True,
                                audio_codec='aac',
                                verbose=False,
                                preset=preset,
                                remove_temp=True)
    else:
        # no reencoding
        shutil.copyfile(video_src_filename, temp_vid_output_file.name)

    if save_path:
        shutil.copyfile(temp_vid_output_file.name, save_path)

    # Temp thumbnail img filename
    temp_thumbnail_file = tempfile.NamedTemporaryFile(prefix='ipae_',
                                                      suffix='.jpg',
                                                      delete=False)
    vidclip.save_frame(temp_thumbnail_file.name, t=thumbnail_frame_ts)

    video_duration = vidclip.duration
    video_size = vidclip.size
    del vidclip  # clear it out

    video_thumbnail_content = temp_thumbnail_file.read()

    if not save_only:
        video_content_len = os.path.getsize(temp_vid_output_file.name)
        video_content = temp_vid_output_file.read()
    else:
        video_content_len = os.path.getsize(save_path)
        video_content = save_path  # return the file path instead

    if video_content_len > 50 * 1024 * 1000:
        raise ValueError('Video file is too big.')

    return video_content, video_size, video_duration, video_thumbnail_content
Exemplo n.º 5
0
from moviepy.video.io.VideoFileClip import VideoFileClip
import datetime

CLIP_DURATION = 10 #in minutes
VIDEO_NAME = "video_comp3.mp4"

VFC = VideoFileClip(VIDEO_NAME)

DURATION = VFC.duration

print("Duration: ",VFC.duration)

# file_names=[]
i=1
for time in range (0,int(DURATION),(CLIP_DURATION*60)):
  timestamp=str(datetime.timedelta(seconds = int (time)))
  # targetname="clip-"+timestamp
  targetname="clip-"+str(i)
  i+=1
  ffmpeg_extract_subclip(VIDEO_NAME, time, time+(CLIP_DURATION*60), targetname="video_clips/"+targetname+".mp4")
  try:
    ffmpeg_extract_audio(("video_clips/"+targetname+".mp4"),str("audio_clips/"+targetname+".wav"),bitrate=500)
  except IOError:
    print("No audio source found in video")

i=1
for time in range (0,int(DURATION),2):
  print("Image: img-"+str(i)+".jpg")
  i+=1
  VFC.save_frame("img_frames/img-"+str(i)+".jpg",t=time,withmask=False)
Exemplo n.º 6
0
image_extra_path = ''
get_images = False
every_second = 0
if len(args) > 3:
    get_images = args['get_images']
    every_second = args['count']
    image_extra_path = 'ad' if args['ad'].strip() == 'True' else 'notad'

print(f"* Start Time: {start_time} , End Time: {end_time} *\n")
video_name = f'{os.path.basename(filename)[:-3].replace(" ", "")}_{str(start_time).replace(":", "-")}_{str(end_time).replace(":","-")}_{image_extra_path}'
new_video_path = os.path.join(VIDEO_CUT_PATH, video_name + '.mp4')

#new_clip.write_videofile(new_video_path, audio_codec='aac')

subprocess.call([
    'ffmpeg', '-ss', f'{start_time}', '-i', f'{filename}', '-to',
    f'{end_time}', '-c', 'copy', f'{VIDEO_CUT_PATH}/{video_name}.mp4'
])

if get_images:
    video_f = VideoFileClip(new_video_path)
    total_frame_count = video_f.duration
    # Calculate how many images i need to cut (total seconds/images to cut per seconds)
    image_cut_count = int(total_frame_count / every_second)
    print(f'[STATUS] Cutting {image_cut_count} Images')
    for image in range(image_cut_count):
        print(f'\r [STATUS] {image_cut_count-image} Images Left', end='')
        video_f.save_frame(
            f'images/{image_extra_path}/{os.path.basename(filename.strip())[0:3]}{random.randrange(1,1000000)}.jpg',
            t=image * every_second)
Exemplo n.º 7
0
    def post(self, request: HttpRequest, *args, **kwargs):
        filename = self.request.GET.get('filename')
        if not filename:
            return {'status': 'error', 'message': 'filename is missing'}, 400

        m = re.match(r'(\d{16})-([\dA-F]{32})\..{3}', filename)
        if not m:
            return {'status': 'error', 'message': 'incorrect filename'}, 400

        dt, hsh = m.groups()
        year, month, day = dt[0:4], dt[4:6], dt[6:8]
        hour, minute, second = dt[8:10], dt[10:12], dt[12:14]
        dt = datetime(*map(int, [year, month, day, hour, minute, second]))

        if filename.endswith('.jpg'):
            is_video = False
            mime = 'image/jpeg'
        elif filename.endswith('.mp4'):
            is_video = True
            mime = 'video/mp4'
        else:
            return {
                'status': 'error',
                'message': 'incorrect file extension'
            }, 400

        try:
            if self.kwargs['destination_id'] == 'undefined':
                destination = Destination.objects.filter(shared=True).first()
                if not destination:
                    raise Destination.DoesNotExist
            else:
                destination = Destination.objects.get(
                    pk=self.kwargs['destination_id'])
        except Destination.DoesNotExist:
            return {'status': 'error', 'message': 'wrong destination id'}, 404

        caption = request.GET.get('caption')
        if caption:
            entry = TitleEntry.objects.filter(hash=hsh).first()
            title = entry.name if entry else '[Unknown application]'
            caption = caption\
                .replace('{title}', title)\
                .replace('{date}', dt.strftime('%Y-%m-%d'))\
                .replace('{time}', dt.strftime('%H:%M:%S'))
            matches = re.findall(r'{datetime:(.+?)}', caption)
            for full_tag, param in matches:
                caption = caption.replace(full_tag, dt.strftime(param))

        uploaded_media = UploadedMedia(destination=destination,
                                       is_video=is_video,
                                       caption=caption)
        uploaded_media.file.save(filename,
                                 SimpleUploadedFile(filename, request.body,
                                                    mime),
                                 save=False)

        if is_video:
            with TemporaryDirectory() as d:
                fpath = os.path.join(d, filename)
                with open(fpath, 'wb') as f:
                    f.write(request.body)
                thumb_name = filename + '.thumb.jpg'
                thumb = os.path.join(d, thumb_name)
                clip = VideoFileClip(fpath)
                if clip.size != [1280, 720]:
                    clip.close()
                    return {'status': 'error', 'message': 'invalid video file'}
                clip.save_frame(thumb, t=1)
                uploaded_media.video_length = clip.duration
                uploaded_media.video_width = clip.size[0]
                uploaded_media.video_height = clip.size[1]
                clip.close()
                with open(thumb, 'rb') as f:
                    uploaded_media.thumb.save(thumb_name,
                                              SimpleUploadedFile(
                                                  thumb_name, f.read(),
                                                  'image/jpeg'),
                                              save=False)
        else:
            try:
                imf = BytesIO(request.body)
                imf.name = 'im.jpg'
                imf.seek(0)
                im = Image.open(imf)  # type: Image.Image
                if im.format != 'JPEG':
                    raise IOError()
            except IOError:
                return {'status': 'error', 'message': 'invalid image file'}

        uploaded_media.save()
        process_upload.apply_async(args=(uploaded_media.pk, ),
                                   shadow=str(uploaded_media))
        return {'status': 'ok'}
Exemplo n.º 8
0
def test_save_frame():
    clip = VideoFileClip("media/big_buck_bunny_432_433.webm")
    location = os.path.join(TMP_DIR, "save_frame.png")
    clip.save_frame(location, t=0.5)
    assert os.path.isfile(location)
    close_all_clips(locals())
Exemplo n.º 9
0
def generateSlides(clip: VideoFileClip, segments: List[Segment], output_dir):
    for seg in segments:
        slidePath = os.path.join(output_dir, '{}.png'.format(seg.startTime))
        slideMidPoint = (seg.startTime + seg.endTime) // 2
        clip.save_frame(slidePath, slideMidPoint)
        seg.imagePath = slidePath
Exemplo n.º 10
0
def extract_first_frame(video_path: str):
    video_clip = VideoFileClip(video_path, audio=False)

    with NamedTemporaryFile(suffix='.jpg') as jpg_file:
        video_clip.save_frame(jpg_file.name)
        yield jpg_file.name