Created
August 21, 2012 17:37
-
-
Save anonymous/3417652 to your computer and use it in GitHub Desktop.
Detect a file's category.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mimetypes | |
import magic | |
magic_mime = magic.open(magic.MAGIC_MIME) | |
magic_mime.load() | |
class FileCategory(list): | |
def __init__(self, *mimes): | |
for mime in mimes: | |
self.append(mime) | |
class FileCategory: | |
IMAGE = FileCategory() | |
AUDIO = FileCategory() | |
VIDEO = FileCategory() | |
DOCUMENT = FileCategory( | |
'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.presentation', | |
'application/msword' #... etc. | |
) | |
ARCHIVE = FileCategory( | |
'application/x-tar', 'application/x-cpio', 'application/x-bzip2', | |
'application/x-7z-compressed' #... etc. | |
) | |
OTHER = FileCategory() | |
def get_file_category(path): | |
mime_type = magic_mime.file(path) | |
if mime_type: | |
mime_type = mime_type.split(';')[0] | |
else: | |
mime_type = mimetypes.guess_type(path)[0] | |
if mime_type.startswith('image/'): | |
return FileCategory.IMAGE | |
if mime_type.startswith('audio/'): | |
return FileCategory.AUDIO | |
if mime_type.startswith('video/'): | |
return FileCategory.VIDEO | |
if mime_type.startswith('text/'): | |
return FileCategory.DOCUMENT | |
if mime_type in FileCategory.IMAGE: | |
return FileCategory.IMAGE | |
if mime_type in FileCategory.AUDIO: | |
return FileCategory.AUDIO | |
if mime_type in FileCategory.VIDEO: | |
return FileCategory.VIDEO | |
if mime_type in FileCategory.DOCUMENT: | |
return FileCategory.DOCUMENT | |
if mime_type in FileCategory.ARCHIVE: | |
return FileCategory.ARCHIVE | |
return FileCategory.OTHER | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment