comixify/api/models.py

58 lines
2.2 KiB
Python
Raw Normal View History

2018-07-31 19:51:39 +00:00
import os
import uuid
import cv2
import pafy
2018-08-20 23:00:22 +00:00
from django.conf import settings
2018-07-31 19:51:39 +00:00
from django.core.files import File
from django.db import models
from api.exceptions import TooLargeFile
from comic_layout.comic_layout import LayoutGenerator
from keyframes.keyframes import KeyFramesExtractor
from style_transfer.style_transfer import StyleTransfer
from utils import jj
2018-07-31 19:51:39 +00:00
class Video(models.Model):
2018-08-20 23:00:22 +00:00
file = models.FileField(blank=False, null=False, upload_to="raw_videos")
2018-07-31 19:51:39 +00:00
timestamp = models.DateTimeField(auto_now_add=True)
def download_from_youtube(self, yt_url):
yt_pafy = pafy.new(yt_url)
# Use the biggest possible quality with file size < MAX_FILE_SIZE and resolution <= 480px
for stream in yt_pafy.videostreams:
if stream.get_filesize() < settings.MAX_FILE_SIZE and int(stream.quality.split("x")[1]) <= 480:
tmp_name = uuid.uuid4().hex + ".mp4"
relative_path = jj('raw_videos', tmp_name)
full_path = jj(settings.MEDIA_ROOT, relative_path)
stream.download(full_path)
self.file.name = relative_path
break
else:
raise TooLargeFile()
def create_comic(self, frames_mode=0, rl_mode=0):
keyframes = KeyFramesExtractor.get_keyframes(video=self, frames_mode=frames_mode, rl_mode=rl_mode)
stylized_keyframes = StyleTransfer.get_stylized_frames(frames=keyframes)
comic_image = LayoutGenerator.get_layout(frames=stylized_keyframes)
return comic_image
2018-07-31 19:51:39 +00:00
class Comic(models.Model):
2018-08-20 23:00:22 +00:00
file = models.FileField(blank=False, null=False, upload_to="comic")
video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name="comic")
2018-07-31 19:51:39 +00:00
@classmethod
def create_from_nparray(cls, nparray_file, video):
2018-08-22 09:52:17 +00:00
if nparray_file.max() <= 1:
nparray_file = (nparray_file * 255).astype(int)
tmp_name = uuid.uuid4().hex + ".png"
cv2.imwrite(jj(settings.TMP_DIR, tmp_name), nparray_file)
with open(jj(settings.TMP_DIR, tmp_name), mode="rb") as tmp_file:
comic_image = File(tmp_file, name=tmp_name)
2018-07-31 19:51:39 +00:00
comic = Comic.objects.create(file=comic_image, video=video)
os.remove(jj(settings.TMP_DIR, tmp_name))
2018-07-31 19:51:39 +00:00
return comic