Ejemplo n.º 1
0
def get_file_hashcode(path):
    video = get_video_properties(path)
    # video = video.__dict__
    # video.pop('_filehandler')
    video = str(video).encode('utf-8')
    hashcode = sha1(video)
    return hashcode.hexdigest()
Ejemplo n.º 2
0
def main(path):
    if path.endswith('.mp4'):
        mp4file = MP4File(path)
        # The 8 boxes required to parse is lacking some information like codec
        # ... hence, a library that uses ffprobe is used...
        vedioProps = get_video_properties(path)
        audioProps = get_audio_properties(path)
        print('..................Summary..................')
        print('The file has a size of: ', mp4file.fsize)
        print('Major Brand: ', mp4file.boxes['ftyp'].box_info['major_brand'])
        print('Compatible Brands: ', mp4file.boxes['ftyp'].box_info['compatible_brands'])
        duration = mp4file.boxes['moov'].child_boxes['mvhd'].box_info['duration']/mp4file.boxes['moov'].child_boxes['mvhd'].box_info['timescale']
        print('Duration is (in seconds): ', duration)
        print('Appoximate bitrate is: ', mp4file.fsize*8/duration)
        print('...................Video...................')
        print('The codec for video: ' + vedioProps['codec_name'])
        if 'trak0' in mp4file.boxes['moov'].child_boxes:
            if mp4file.boxes['moov'].child_boxes['trak0'].child_boxes['tkhd'].box_info['volume'] == 0:
                print('The width for video: ' + str(mp4file.boxes['moov'].child_boxes['trak0'].child_boxes['tkhd'].box_info['width']))
                print('The height for video: ' + str(mp4file.boxes['moov'].child_boxes['trak0'].child_boxes['tkhd'].box_info['height']))
            else:
                print('The width for video: ' + str(mp4file.boxes['moov'].child_boxes['trak1'].child_boxes['tkhd'].box_info['width']))
                print('The height for video: ' + str(mp4file.boxes['moov'].child_boxes['trak1'].child_boxes['tkhd'].box_info['height']))
        print('The avg_frame_rate for video: ' + str(eval(vedioProps['avg_frame_rate'])))
        print('...................Audio...................')
        print('The codec for audio: ' + audioProps['codec_name'])
        print('The sample rate for audio: ' + audioProps['sample_rate'])
        print('The number of channels for audio: ' + str(audioProps['channels']))
        print('The bit_rate for audio: ' + audioProps['bit_rate'])
    else:
        logging.error('File format not supported')
Ejemplo n.º 3
0
def audio_matching(audio, folder):
    '''find matching video files for audio and define the video resolution'''
    ### Get Values ###
    values = 'static/audioClips' + folder + '/values.txt'

    with open(values) as f:
        duration = f.readline().strip()
        arousal_string = f.readline().strip()
        valence_string = f.readline().strip()

    arousal = [float(value.strip()) for value in arousal_string.split(', ')]
    valence = [float(value.strip()) for value in valence_string.split(', ')]

    ########## Matching ##########
    matching_method = session['files']['matching']

    if "approx" in matching_method:
        mode = "standard" if matching_method == "approx" else "mse"

        if matching_method == "approx_w":
            mode = "weighted"

        matching_files, matching_indexes = approximation_matching(
            folder, "audio", mode)

    elif "offline" in matching_method:
        mode = "standard" if matching_method == "offline" else "mse"

        if matching_method == "offline_w":
            mode = "weighted"

        matching_files, matching_indexes = offline_matching(
            folder, "audio", mode)

    else:
        matching_files, matching_indexes = random_matching(folder, "audio")

    for i in range(0, len(matching_files)):
        matching_files[i] = encode(matching_files[i])

    session['files'] = {
        'matching_files': matching_files,
        'matching_indexes': matching_indexes
    }

    ########## Get video resolution ##########
    max_width = 0.0
    max_height = 0.0

    for video in session['files']['matching_files']:
        props = get_video_properties('static/datasets/video/' + decode(video) +
                                     '.mp4')
        if props['width'] > max_width:
            max_width = props['width']
        if props['height'] > max_height:
            max_height = props['height']

    resolution = {"width": max_width, "height": max_height}

    return merge_audio_result(audio, resolution)
Ejemplo n.º 4
0
    async def get_properties(self):
        """Get the video properties like codec, resolution.Returns Video properties saved in a Dictionary."""
        """
        NamedTemporaryFile is too hard to use portably when you need to open the file by name after writing it.
        On posix you can open the file for reading by name without closing it first.
        But on Windows, To do that you need to close the file first, which means you have to pass delete=False,
        which in turn means that you get no help in cleaning up the actual file resource.
        """

        fbytes = await self.get_file_bytes()  # get bytes of file

        temp_vid = tempfile.NamedTemporaryFile(
            prefix="opsdroid_vid_",
            delete=False)  # create a file to store the bytes
        temp_vid.write(fbytes)
        temp_vid.close()

        try:
            vid_details = get_video_properties(temp_vid.name)
            os.remove(temp_vid.name)  # delete the temp file
            return vid_details
        except RuntimeError as error:
            if "ffmpeg" in str(error).lower():
                _LOGGER.warning(
                    _("Video events are not supported unless ffmpeg is installed. Install FFMPEG on your system. Here is the error: "
                      ))
                _LOGGER.warning(_(error))
                os.remove(temp_vid.name)  # delete the temp file
Ejemplo n.º 5
0
def check_video_validation(total_parts, source_folder):
    """ combine a chunked file to check validation of proRes video.
    """

    dest = os.path.join(source_folder, 'video_chunk')

    with open(dest, 'wb+') as destination:
        if int(sys.version[:1]) >= 3:
            for i in range(int(total_parts)):
                part = os.path.join(source_folder, str(i))
                with open(part, 'rb') as source:
                    destination.write(source.read())
        else:
            for i in xrange(int(total_parts)):
                part = os.path.join(source_folder, str(i))
                with open(part, 'rb') as source:
                    destination.write(source.read())

    try:
        props = get_video_properties(dest)
        print (props)

        if props['codec_name'] == 'proRes':
            return True

    except Exception as e:
        print(e)

    return False
Ejemplo n.º 6
0
def get_new_vid_name(video):
    extension = filetype.guess_extension(video)
    properties = videoprops.get_video_properties(video)
    vid_date = properties['tags']['creation_time']
    formated_vid_date = vid_date.replace("-", "").replace("T",
                                                          "").replace(":", "")
    new_name = f"vid_{formated_vid_date[:8]}_{formated_vid_date[8:14]}.{extension}"
    return new_name
Ejemplo n.º 7
0
def get_max_size(videos):
    max_width = 0
    max_height = 0

    for v in videos:
        props = get_video_properties(v)
        max_width = max(max_width, props['width'])
        max_height = max(max_height, props['height'])

    return max_width, max_height
Ejemplo n.º 8
0
def get_video_data(filename):
    if os.path.exists(filename):
        props = videoprops.get_video_properties(filename)
    else:
        raise FileNotFoundError(
            errno.ENOENT, os.strerror(errno.ENOENT), filename)

    fields = ['codec_name', 'width', 'height']
    result = {prop: props[prop] for prop in fields}
    return result
Ejemplo n.º 9
0
def convert_video_thumbnail(data, context):

    print(data)

    if data['contentType'].startswith('video/'):

        bucket = client.get_bucket(data['bucket'])
        name = data['name']

        file_name = '/tmp/' + name
        print(file_name)

        thumbnail_file_name = '/tmp/' + name.split('.')[0] + '.png'
        print(thumbnail_file_name)

        try:
            os.remove(file_name)
        except OSError:
            pass

        try:
            os.remove(thumbnail_file_name)
        except OSError:
            pass

        print("File has been removed")

        # Downloading the video to the cloud functions
        blob = bucket.get_blob(name)
        blob.download_to_filename(file_name)

        print("Video Downloaded")

        props = get_video_properties(file_name)

        if os.path.exists(file_name):
            print("NEW MP4 EXISTS")
            check_output('ffmpeg  -itsoffset -4  -i ' + file_name +
                         ' -vcodec mjpeg -vframes 1 -an -f rawvideo -s ' +
                         str(props['width']) + 'x' + str(props['height']) +
                         ' ' + thumbnail_file_name,
                         shell=True)
            thumbnail_blob = bucket.blob(name.split('.')[0] + '.png')
            thumbnail_blob.upload_from_filename(thumbnail_file_name)
        else:
            print("MP4 not created")

        print("uploaded")

    else:
        print("Not a Video")
Ejemplo n.º 10
0
def get_quality(file):
    video = get_video_properties(file)

    if video['width'] >=3800 :
        video_quality = "4K"
    elif video['width'] >= 2000 and video['width'] < 3800:
        video_quality = "2K"
    elif video['width'] >= 1700 and video['width'] < 2000:
        video_quality = "FullHD"
    elif video['width'] >= 1000 and video['width'] < 1700:
        video_quality = "HD"
    elif video['width'] < 1000:
        video_quality = "SD"

    return video_quality
Ejemplo n.º 11
0
def resize(videos, maxw, maxh):
    PAD_OPTIONS = {
        'width': '{}'.format(maxw),
        'height': '{}'.format(maxh),
        'x': '(ow-iw)/2',
        'y': '(oh-ih)/2',
    }
    for v in videos:
        props = get_video_properties(v)

        (ffmpeg.input(v).filter(
            "scale",
            size="{}:{}".format(maxw, maxh),
            force_original_aspect_ratio='decrease').filter_(
                "pad",
                **PAD_OPTIONS).filter("setsar", 1).output('{}m.mp4'.format(
                    v[:v.find(".mp4")])).global_args('-y').run())
Ejemplo n.º 12
0
import subprocess
import time


input_path = 'input/Test_Set/'
output_path = 'output/Test_Set/'
files = [f for f in listdir(input_path) if isfile(join(input_path, f))]


for file in files:

	input_full_path  = input_path + file
	output_full_path = output_path + file[:-4]

	props = get_video_properties(input_full_path)

	print(f'''Resolution: {props['width']}×{props['height']}''')

	new_w = 346
	new_h = math.ceil((new_w * props['height'])/props['width'])

	print(f'''New resolution: {new_w}×{new_h}''')

	start_time = time.time()
	subprocess.call('./run_v2e.sh ' + input_full_path + ' ' + output_full_path + ' ' + str(new_w) + ' ' + str(new_h), shell=True)
	print("--- %s seconds ---" % (time.time() - start_time))

	print('\n')

Ejemplo n.º 13
0
def video_info(video_path):
    video_properties = get_video_properties(video_path)
    audio_properties = get_audio_properties(video_path)
    return video_properties, audio_properties
Ejemplo n.º 14
0
    def post(self, request, format=None):
        print("Entered Here")
        print((request.data))
        destination_bucket = 'video-streaming-project-bucket'
        data = {
            "status_code": 200,
            "message": "Request is accepted",
            "result": {}
        }

        storage_client = storage.Client()
        file_serializer = FileSerializer(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
            video_id = uuid.uuid4()
            video_id_str = str(video_id).replace("-", "")
            mypath = os.path.join(os.getcwd(), "media")
            onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
            filename = onlyfiles[0]
            if ((os.path.exists(
                    os.path.join(os.getcwd(), "media",
                                 onlyfiles[0].split(".")[0] +
                                 ".mp4"))) == False):
                mp4_conversion_cmd = 'ffmpeg -i ' + '"' + os.path.join(
                    os.getcwd(), "media",
                    onlyfiles[0]) + '"' + " " + '"' + os.path.join(
                        os.getcwd(), "media",
                        onlyfiles[0].split(".")[0] + ".mp4") + '"'

                filename = filename.split(".")[0] + ".mp4"
                p = subprocess.Popen(mp4_conversion_cmd,
                                     stdout=subprocess.PIPE,
                                     shell=True)
                p.wait()
                out, err = p.communicate()
            video_description = 'file uploaded'

            result = subprocess.run([
                "ffprobe", "-v", "error", "-show_entries", "format=duration",
                "-of", "default=noprint_wrappers=1:nokey=1",
                os.path.join(os.getcwd(), "media", filename)
            ],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            if (result.stdout != 'N/A\n'):
                video_duration = float(result.stdout)
            else:
                video_duration = 0
            props = get_video_properties(
                os.path.join(os.getcwd(), "media", filename))
            video_resolution = str(props['width']) + "X" + str(props['height'])
            video_encoding = str(props['codec_name'])
            video_size = os.path.getsize(
                os.path.join(os.getcwd(), "media", filename))
            thumbnail_command = 'ffmpeg -i ' + '"' + os.path.join(
                os.getcwd(), "media", filename
            ) + '"' + ' -ss 00:00:01.000 -vframes 1 ' + '"' + os.path.join(
                os.getcwd(), "media", video_id_str + '.png') + '"'
            video_thumbnail = subprocess.Popen(thumbnail_command,
                                               shell=True,
                                               stdout=subprocess.PIPE)
            out, err = video_thumbnail.communicate()
            bucket = storage_client.bucket(destination_bucket)
            destination_blob_name = video_id_str + '/video/' + filename
            blob = bucket.blob(destination_blob_name)
            blob.upload_from_filename(
                os.path.join(os.getcwd(), "media", filename))
            destination_blob_name_thumbnail = 'thumbnail/' + video_id_str + ".png"
            blob = bucket.blob(destination_blob_name_thumbnail)
            blob.upload_from_filename(
                os.path.join(os.getcwd(), "media", video_id_str + '.png'))
            blob.make_public()
            video_clip_command = 'ffmpeg -ss 00:00:05 -i ' + '"' + os.path.join(
                os.getcwd(), "media", filename
            ) + '"' + ' -t 00:00:05 -vcodec copy -acodec copy ' + '"' + os.path.join(
                os.getcwd(), "media", video_id_str + '.mp4') + '"'
            video_clip = subprocess.Popen(video_clip_command,
                                          shell=True,
                                          stdout=subprocess.PIPE)
            out, err = video_clip.communicate()
            destination_blob_name_clip = 'clip/' + video_id_str + ".mp4"
            blob1 = bucket.blob(destination_blob_name_clip)
            blob1.upload_from_filename(
                os.path.join(os.getcwd(), "media", video_id_str + '.mp4'))
            blob1.make_public()
            print("Blob {} is publicly accessible at {}".format(
                blob.name, blob.public_url))
            print(video_resolution)
            data['result']['video_id'] = video_id
            VideoDetails.objects.create(video_id=video_id,
                                        video_name=filename,
                                        video_description=video_description,
                                        thumbnail_url=blob.public_url,
                                        video_duration=video_duration,
                                        video_encoding=video_encoding,
                                        video_path="gs://" +
                                        destination_bucket + "/" +
                                        destination_blob_name,
                                        video_size=video_size,
                                        video_category=video_description,
                                        video_resolution=video_resolution,
                                        clip_url=blob1.public_url)
            cmd = 'rmdir /s/q ' + '"' + os.path.join(os.getcwd(),
                                                     "media") + '"'
            delete_folder = subprocess.Popen(cmd,
                                             shell=True,
                                             stdout=subprocess.PIPE)
            out, err = delete_folder.communicate()
            hostname = socket.gethostname()
            IPAddr = socket.gethostbyname(hostname)
            response = requests.post('http://192.168.0.22:8000/encoding',
                                     data={'video_id': str(video_id)})

            try:
                os.mkdir(os.path.join(os.getcwd(), "media"))
            except OSError:
                print("Creation of the directory %s failed" % path)
            if response.status_code == 200:
                return Response(data, status=status.HTTP_201_CREATED)
            else:
                data['status_code'] = 400
                data['message'] = "Upload failed"
                return Response(data, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(file_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 15
0
    def post(self, request, format=None):
        try:
            data = {"status_code": 200, "message": "Requested Accepted"}
            video_id = request.data['video_id']
            video_download_directory = '/tmp'
            os.mkdir(os.path.join(video_download_directory, video_id))
            object_download_path = os.path.join(video_download_directory,
                                                video_id, "original_video.mp4")
            storage_client = storage.Client()
            video_path = list(
                VideoDetails.objects.filter(
                    video_id=video_id).values('video_path'))[0]['video_path']
            print(video_path)
            bucket_name = video_path.split("/")[2]
            object_path = "/".join(video_path.split("/")[3:])
            bucket = storage_client.bucket(bucket_name)
            blob = bucket.blob(object_path)
            blob.download_to_filename(object_download_path)
            video_resolution_list = list(
                VideoEncodingFormat.objects.filter().values(
                    'resolution'))[0:15]
            width_list = []
            height_list = []
            for i in range(len(video_resolution_list)):
                width, height = video_resolution_list[i]['resolution'].split(
                    "X")
                width_list.append(int(width))
                height_list.append(int(height))

            min_w = 3360
            min_h = 2100
            index = 0
            props = get_video_properties(
                os.path.join(video_download_directory, str(video_id),
                             'original_video.mp4'))
            print(str(props['width']) + "X" + str(props['height']))
            for i in range(len(width_list)):
                if ((int(props['width']) - width_list[i]) >= 0
                        and (int(props['width']) - width_list[i]) <= min_w
                        and (int(props['height']) - height_list[i]) >= 0
                        and (int(props['height']) - height_list[i]) <= min_h):
                    min_h = (props['height'] - height_list[i])
                    min_w = (props['width'] - width_list[i])
                    index = i
            os.mkdir(
                os.path.join(video_download_directory, video_id, 'encoding'))
            for i in range(0, index + 1):
                cmd = 'ffmpeg -i ' + '"' + os.path.join(
                    video_download_directory, str(video_id),
                    'original_video.mp4'
                ) + '"' + ' -s ' + str(width_list[i]) + 'x' + str(
                    height_list[i]) + ' -c:a copy ' + '"' + os.path.join(
                        video_download_directory, video_id, 'encoding',
                        str(i + 1) + '.mp4') + '"'
                cmd_output = subprocess.Popen(cmd,
                                              shell=True,
                                              stdout=subprocess.PIPE)
                cmd_output.wait()
                out, err = cmd_output.communicate(input=None, timeout=None)
                webm_cmd = 'ffmpeg -i ' + '"' + os.path.join(
                    video_download_directory, str(video_id),
                    'original_video.mp4'
                ) + '"' + ' -s ' + str(width_list[i]) + 'x' + str(
                    height_list[i]
                ) + ' -c:v libvpx-vp9 -crf 30 -b:v 0 ' + '"' + os.path.join(
                    video_download_directory, video_id, 'encoding',
                    str(i + 1) + '.webm') + '"'
                webm_cmd_output = subprocess.Popen(webm_cmd,
                                                   shell=True,
                                                   stdout=subprocess.PIPE)
                out, err = webm_cmd_output.communicate(input=None,
                                                       timeout=None)
                ogg_cmd = 'ffmpeg -i ' + '"' + os.path.join(
                    video_download_directory, video_id, 'encoding',
                    str(i + 1) + '.mp4'
                ) + '"' + ' -c:v libtheora -q:v 7 -c:a libvorbis -q:a 4 ' + '"' + os.path.join(
                    video_download_directory, video_id, 'encoding',
                    str(i + 1) + '.ogv') + '"'
                ogg_cmd_output = subprocess.Popen(ogg_cmd,
                                                  shell=True,
                                                  stdout=subprocess.PIPE)
                out, err = ogg_cmd_output.communicate(input=None, timeout=None)
                bucket = storage_client.bucket(bucket_name)
                mp4_destination_blob_name = str(video_id).replace(
                    "-", "") + "/encoding/" + str(i + 1) + '.mp4'
                mp4_blob = bucket.blob(mp4_destination_blob_name)
                mp4_blob.upload_from_filename(
                    os.path.join(video_download_directory, video_id,
                                 'encoding',
                                 str(i + 1) + '.mp4'))
                web_destination_blob_name = str(video_id).replace(
                    "-", "") + "/encoding/" + str(i + 1) + '.webm'
                web_blob = bucket.blob(web_destination_blob_name)
                web_blob.upload_from_filename(
                    os.path.join(video_download_directory, video_id,
                                 'encoding',
                                 str(i + 1) + '.webm'))
                ogg_destination_blob_name = str(video_id).replace(
                    "-", "") + "/encoding/" + str(i + 1) + '.ogv'
                ogg_blob = bucket.blob(ogg_destination_blob_name)
                ogg_blob.upload_from_filename(
                    os.path.join(video_download_directory, video_id,
                                 'encoding',
                                 str(i + 1) + '.ogv'))
                video_id_object = VideoDetails.objects.get(video_id=video_id)
                mp4_encoding_id_object = VideoEncodingFormat.objects.get(id=i +
                                                                         1)
                web_encoding_id_object = VideoEncodingFormat.objects.get(id=i +
                                                                         16)
                ogv_encoding_id_object = VideoEncodingFormat.objects.get(id=i +
                                                                         31)
                VideoEncodingDetails.objects.create(
                    video_id=video_id_object,
                    encoding_id=mp4_encoding_id_object,
                    video_path='gs://' + bucket_name + "/" +
                    str(video_id).replace("-", "") + "/encoding/" +
                    str(i + 1) + '.mp4')
                VideoEncodingDetails.objects.create(
                    video_id=video_id_object,
                    encoding_id=web_encoding_id_object,
                    video_path='gs://' + bucket_name + "/" +
                    str(video_id).replace("-", "") + "/encoding/" +
                    str(i + 1) + '.webm')
                VideoEncodingDetails.objects.create(
                    video_id=video_id_object,
                    encoding_id=ogv_encoding_id_object,
                    video_path='gs://' + bucket_name + "/" +
                    str(video_id).replace("-", "") + "/encoding/" +
                    str(i + 1) + '.ogv')

            cmd = 'rmdir /s/q ' + '"' + os.path.join(video_download_directory,
                                                     video_id) + '"'
            delete_folder = subprocess.Popen(cmd,
                                             shell=True,
                                             stdout=subprocess.PIPE)
            out, err = delete_folder.communicate()
            return Response(data, status=status.HTTP_200_OK, headers=None)
        except Exception as e:
            print("****************************************************")
            print(e)
            print("****************************************************")
            data['status_code'] = 400
            data['message'] = str(e)
            return Response(data, status=status.HTTP_200_OK, headers=None)
Ejemplo n.º 16
0
    def post(self, request, format=None):
        """
            @param:
                request = Input Request for extracting video details
            @returns:
                The request accepted message and video details extracted and stored in the database

        """
        print("Entered Here1234")
        destination_bucket = 'video-streaming-project-bucket'
        try:
            data = {
                "status_code": 200,
                "message": "Request is accepted",
                "video_id": ""
            }
            video_download_directory = '/tmp'
            try:
                if path.exists(video_download_directory):
                    pass
            except Exception as e:
                os.mkdir(video_download_directory)
            print(request.data)
            video_request_serializer = VideoUploadRequestSerializer(
                data=request.data)

            if (video_request_serializer.is_valid()):
                print("Entered Here too")
                is_bucket_path = request.data['is_bucket_path']
                if (is_bucket_path):
                    bucket_path = request.data['path']
                    storage_client = storage.Client()
                    bucket_name = bucket_path.split("/")[2]
                    prefix = "/".join(bucket_path.split("/")[3:])
                    filename = bucket_path.split("/")[-1]
                    blobs = storage_client.list_blobs(bucket_name,
                                                      prefix=prefix)
                    list_of_files = []
                    for blob in blobs:
                        if str(blob.name).endswith("/"):
                            pass
                        else:
                            list_of_files.append(str(blob.name))
                    print(list_of_files)
                    for i in range(len(list_of_files)):
                        video_id = uuid.uuid4()
                        video_id_str = str(video_id).replace("-", "")
                        video_name = ".".join(
                            list_of_files[i].split("/")[-1]).split(".")[:-1]
                        video_description = list_of_files[i].split("/")[1]

                        if (path.exists(
                                os.path.join(video_download_directory,
                                             str(video_id_str), 'video'))):
                            pass
                        else:
                            print("Entered Here too")
                            os.mkdir(
                                os.path.join(video_download_directory,
                                             str(video_id_str)))
                            os.mkdir(
                                os.path.join(video_download_directory,
                                             str(video_id_str), 'video'))
                        try:
                            cmd = (' '.join([
                                'gsutil', '-m', 'cp',
                                'gs://' + bucket_name + '/' + list_of_files[i],
                                "\"" +
                                os.path.join(video_download_directory,
                                             str(video_id_str), 'video') + "\""
                            ]))
                            p = subprocess.Popen(cmd,
                                                 stdout=subprocess.PIPE,
                                                 shell=True)
                            p.wait()
                            out, err = p.communicate()
                        except Exception as e:
                            print("Entered Here1111")
                            print(e)
                        mp4_conversion_cmd = 'ffmpeg -i ' + '"' + os.path.join(
                            video_download_directory, str(video_id_str),
                            'video',
                            filename) + '"' + " " + '"' + os.path.join(
                                video_download_directory, str(video_id_str),
                                'video',
                                filename.split(".")[0] + ".mp4") + '"'
                        print(mp4_conversion_cmd)
                        filename = filename.split(".")[0] + ".mp4"
                        p = subprocess.Popen(mp4_conversion_cmd,
                                             stdout=subprocess.PIPE,
                                             shell=True)
                        p.wait()
                        out, err = p.communicate()
                        result = subprocess.run([
                            "ffprobe", "-v", "error", "-show_entries",
                            "format=duration", "-of",
                            "default=noprint_wrappers=1:nokey=1",
                            os.path.join(video_download_directory,
                                         str(video_id_str), 'video', filename)
                        ],
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.STDOUT)
                        if (result.stdout != 'N/A\n'):
                            video_duration = float(result.stdout)
                        else:
                            video_duration = 0
                        props = get_video_properties(
                            os.path.join(video_download_directory,
                                         str(video_id_str), 'video', filename))
                        video_resolution = str(props['width']) + "X" + str(
                            props['height'])
                        video_encoding = str(props['codec_name'])
                        video_size = os.path.getsize(
                            os.path.join(video_download_directory,
                                         str(video_id_str), 'video', filename))
                        thumbnail_command = 'ffmpeg -i ' + '"' + os.path.join(
                            video_download_directory, str(video_id_str),
                            "video", filename
                        ) + '"' + ' -ss 00:00:01.000 -vframes 1 ' + '"' + os.path.join(
                            video_download_directory, str(video_id_str),
                            'thumbnail.png') + '"'
                        video_thumbnail = subprocess.Popen(
                            thumbnail_command,
                            shell=True,
                            stdout=subprocess.PIPE)
                        out, err = video_thumbnail.communicate()
                        video_clip_command = 'ffmpeg -ss 00:00:05 -i ' + '"' + os.path.join(
                            video_download_directory, str(video_id_str),
                            "video", filename
                        ) + '"' + ' -t 00:00:05 -vcodec copy -acodec copy ' + '"' + os.path.join(
                            video_download_directory, str(video_id_str),
                            'clip.mp4') + '"'
                        video_clip = subprocess.Popen(video_clip_command,
                                                      shell=True,
                                                      stdout=subprocess.PIPE)
                        out, err = video_clip.communicate()
                        bucket = storage_client.bucket(destination_bucket)
                        destination_blob_name = video_id_str + '/video/' + filename
                        blob = bucket.blob(destination_blob_name)
                        blob.upload_from_filename(
                            os.path.join(video_download_directory,
                                         str(video_id_str), 'video', filename))
                        destination_blob_name_thumbnail = 'thumbnail/' + video_id_str + ".png"
                        blob = bucket.blob(destination_blob_name_thumbnail)
                        blob.upload_from_filename(
                            os.path.join(video_download_directory,
                                         str(video_id_str), 'thumbnail.png'))
                        blob.make_public()
                        destination_blob_name_clip = 'clip/' + video_id_str + ".mp4"
                        blob1 = bucket.blob(destination_blob_name_clip)
                        blob1.upload_from_filename(
                            os.path.join(video_download_directory,
                                         str(video_id_str), 'clip.mp4'))
                        blob1.make_public()

                        cmd = 'rmdir /s/q ' + '"' + os.path.join(
                            video_download_directory, video_id_str) + '"'
                        delete_folder = subprocess.Popen(
                            cmd, shell=True, stdout=subprocess.PIPE)
                        out, err = delete_folder.communicate()
                        VideoDetails.objects.create(
                            video_id=video_id,
                            video_name=filename,
                            video_description=video_description,
                            thumbnail_url=blob.public_url,
                            video_duration=video_duration,
                            video_encoding=video_encoding,
                            video_path="gs://" + destination_bucket + "/" +
                            destination_blob_name,
                            video_size=video_size,
                            video_category=video_description,
                            video_resolution=video_resolution,
                            clip_url=blob1.public_url)
            else:
                data['status_code'] = 400
                data['message'] = 'Bad Request'
            return Response(data, status=status.HTTP_200_OK, headers=None)
        except Exception as e:
            print(e)
            data['message'] = str(e)
            return Response(data, status=status.HTTP_200_OK, headers=None)
Ejemplo n.º 17
0
def send_telegram(input, type, bot=telegram_bot_token, notification=False):
    notification = not notification
    if type == "text":
        r = requests.post(
            "https://api.telegram.org/" + bot + "/sendMessage",
            params={
                "chat_id": "1024110161",
                "text": input,
                "disable_notification": notification,
            },
        )
    elif type == "voice":
        r = requests.post(
            "https://api.telegram.org/" + bot + "/sendVoice",
            params={
                "chat_id": "1024110161",
                "disable_notification": notification
            },
            files={"voice": open(input, "rb")},
        )
    elif type == "animation":
        r = requests.post(
            "https://api.telegram.org/" + bot + "/sendAnimation",
            params={
                "chat_id": "1024110161",
                "disable_notification": notification
            },
            files={"animation": open(input, "rb")},
        )
    elif type == "photo":
        r = requests.post(
            "https://api.telegram.org/" + bot + "/sendPhoto",
            params={
                "chat_id": "1024110161",
                "photo": input,
                "disable_notification": notification,
            },
        )
    elif type == "video_file":
        width = get_video_properties(input)["width"]
        height = get_video_properties(input)["height"]
        r = requests.post(
            "https://api.telegram.org/" + bot + "/sendVideo",
            params={
                "chat_id": "1024110161",
                "width": width,
                "height": height,
                "disable_notification": notification,
            },
            files={"video": open(input, "rb")},
        )
    elif type == "video_url":
        r = requests.post(
            "https://api.telegram.org/" + bot + "/sendVideo",
            params={
                "chat_id": "1024110161",
                "video": input,
                "disable_notification": notification,
            },
        )
    return r
Ejemplo n.º 18
0
def resolution(item):
    vProp = get_video_properties(item)
    x = vProp['width']
    y = vProp['height']
    return x, y
import os
from PIL import Image
from datetime import datetime
from videoprops import get_video_properties

folder = 'video/'
# folder_success='video_success/'
for subdir, dirs, files in os.walk(folder):
    for file in files:
        path_video = os.path.join(folder, file)
        # path_move = os.path.join(folder_success,file)
# filevideo='P_one2.mov'
# # path_video='video/IMG_9556.MOV'
# path_video=os.path.join(folder,filevideo)

props_2 = get_video_properties(path_video)


def cal_resolution(props_2):
    rotate = False
    width = props_2['width']
    height = props_2['height']
    if width < height:
        reso = width / height
    else:
        reso = height / width
        rotate = True
    if reso == 0.5625:
        resize_v = 576
    else:
        resize_v = 768
Ejemplo n.º 20
0
def set_meta_mp4(filepath: str) -> None:
    stinfo = os.stat(filepath)
    file_name = os.path.basename(filepath)
    actual_time = get_ntime(file_name)
    base_time = ''
    if not actual_time:
        actual_time = get_mtime(filepath)
        base_time = timestamp_to_name(actual_time)

    vid_props = get_video_properties(filepath)
    try:
        aud_props = get_audio_properties(filepath)
        channels = aud_props["channels"]
    except RuntimeError as ex:
        log.warning(ex)
        channels = 0
    #print(vid_props['tags']['creation_time'])
    bitrate = int(vid_props["bit_rate"]) // 1024
    log.debug(f'{bitrate=}kBs {channels=}')
    if bitrate > 400:
        flags = '-ac 1 -vcodec libx264 -vf "scale=iw/2:ih/2" -crf 25'
        t = 'compress'
    else:
        if channels == 0:
            flags = '-codec copy'
            t = 'copy'
        elif channels == 1:
            flags = '-codec copy'
            t = 'copy'
        elif channels == 2:
            flags = '-ac 1 -c:v copy'
            t = 'audio'
        else:
            raise RuntimeError(f'Strange channels count: {channels}')
    ctime = dt.datetime.fromtimestamp(actual_time)
    #if override:
    #    ctime.replace(year=2018, month=6, day=30)
    cmd = f'ffmpeg -i "{filepath}" -metadata creation_time="{ctime}" {flags} -y tmp.mp4'
    log.debug(' '*12 + f'Call: {cmd}')
    completed = subprocess.run(cmd, capture_output=True)
    if completed.returncode != 0:
        log.error(f'Problem retcode={completed.returncode} with: {cmd}')
    if t == 'compress':
        for line in completed.stderr.decode("utf-8").splitlines():
            log.debug(' '*12 + 'stderr>' + line)
        for line in completed.stdout.decode("utf-8").splitlines():
            log.debug(' '*12 + 'stdout>' + line)
    if base_time:
        directory = os.path.dirname(filepath)
        file_name = base_time + " " + file_name
        new_filepath = os.path.join(directory, file_name)
    else:
        new_filepath = filepath

    new_filepath = new_filepath.replace('.avi', '.mp4')
    # TODO: Add _crf25
    if not '_crf25' in new_filepath:
        new_filepath = new_filepath.replace('.mp4', '_crf25.mp4')
    
    #if override:
    #    new_filepath = override_filepath(new_filepath)
    shutil.move('tmp.mp4', new_filepath)
    # Keep accesstime, change modifiedtime
    os.utime(filepath, (stinfo.st_atime, actual_time))
def predict_video(model, input_video, output_video, output_file, frame_rate=2):
    # start

    # args = get_arguments()
    # input_video = args.input_video
    # output_video = args.output_video
    # output_file = args.output_file

    # input_video = "sample_video/IMG_0119.MOV"
    # output_video = "output/output_IMG_0119.MOV"

    # video_size = (540, 960)
    # video_size = (1080, 1920)
    # video_size = (1920, 1080)
    # video_size=(960, 540)

    # remove existed output video
    if os.path.exists(output_video):
        os.remove(output_video)
        print("Removed {}".format(output_video))

    print("input_video: ", input_video)
    # video path
    cap = cv2.VideoCapture(input_video)
    video_info = get_video_properties(input_video)

    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)  # float
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # float

    print("Video actual size: w={} h={}".format(width, height))
    video_size = (int(width), int(height))
    output_video_size = (960, 540)

    need_rotate = False
    rotate_side = 0

    if "rotate" in video_info["tags"]:
        if video_info["tags"]["rotate"] == '90' or video_info["tags"][
                "rotate"] == '-90':
            video_size = (int(height), int(width))
            output_video_size = (540, 960)

        if video_info["tags"]["rotate"] == '90':
            rotate_side = cv2.ROTATE_90_CLOCKWISE
        elif video_info["tags"]["rotate"] == '-90':
            rotate_side = cv2.ROTATE_90_COUNTERCLOCKWISE
        elif video_info["tags"]["rotate"] == '180':
            rotate_side = cv2.ROTATE_180_CLOCKWISE

        need_rotate = True

    # fourcc = cv2.VideoWriter_fourcc(*'vp80')
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter(output_video, fourcc, 20.0, output_video_size)

    # load model
    frame_count = 0
    next_frame = 0
    license_list = []

    while cap.isOpened():
        ret, frame = cap.read()
        if frame is None:
            print("[INFO] End of Video")
            break

        frame_count += 1

        if need_rotate:
            frame = cv2.rotate(frame, rotate_side)

        frame = cv2.resize(frame, output_video_size)

        # skip frame for faster processing
        if frame_count < next_frame:
            out.write(frame)
            continue

        next_frame = frame_count + frame_rate

        print("frame_count: ", frame_count)

        # frame = cv2.resize(frame, video_size)
        try:
            processed_frame, all_license_plates, total_cars = predict_one_image(
                frame, model, name="frame_{}".format(frame_count))
            license_list.append(all_license_plates)

            if total_cars == 0:
                next_frame = frame_count + frame_rate * 5
        except Exception as ex:
            print("=======> Error: ", ex)
            print(traceback.format_exc())
            # or
            print(sys.exc_info()[2])
            processed_frame = frame

        # cv2.imshow('video', processed_frame)
        # cv2.imwrite("/src/output/images/frame_{}.jpeg".format(frame_count), processed_frame)

        out.write(processed_frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
    # choose license plate
    selected_license_plates = select_license_plate(license_list,
                                                   queue_size=5,
                                                   match_size=3)

    print("selected_license_plates: ", selected_license_plates)

    # write to result file
    writer = open(output_file, "w")
    for cur_license in selected_license_plates:
        if cur_license is not None:
            writer.write(cur_license + "\n")
    writer.close()

    print("Finished processing video")