Skip to content

Commit

Permalink
finish convert and compressed
Browse files Browse the repository at this point in the history
  • Loading branch information
teukufaiz committed Apr 2, 2023
1 parent c4d37ed commit 593a730
Show file tree
Hide file tree
Showing 27 changed files with 368 additions and 0 deletions.
Binary file added db.sqlite3
Binary file not shown.
22 changes: 22 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tools.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
Empty file added tools/__init__.py
Empty file.
Binary file added tools/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added tools/__pycache__/settings.cpython-310.pyc
Binary file not shown.
Binary file added tools/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file added tools/__pycache__/wsgi.cpython-310.pyc
Binary file not shown.
16 changes: 16 additions & 0 deletions tools/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for tools project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tools.settings')

application = get_asgi_application()
127 changes: 127 additions & 0 deletions tools/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""
Django settings for tools project.
Generated by 'django-admin startproject' using Django 4.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-xn!2g32y=%%a#xm^8pz#@i)+s+8pu=vqk@--f&7eokc0h3gb=s'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'videotools'
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'tools.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'tools.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = ["*"]
22 changes: 22 additions & 0 deletions tools/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""tools URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('admin/', admin.site.urls),
path('',include('videotools.urls')),
]
16 changes: 16 additions & 0 deletions tools/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for tools project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tools.settings')

application = get_wsgi_application()
Empty file added videotools/__init__.py
Empty file.
Binary file added videotools/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added videotools/__pycache__/admin.cpython-310.pyc
Binary file not shown.
Binary file added videotools/__pycache__/apps.cpython-310.pyc
Binary file not shown.
Binary file added videotools/__pycache__/models.cpython-310.pyc
Binary file not shown.
Binary file added videotools/__pycache__/urls.cpython-310.pyc
Binary file not shown.
Binary file added videotools/__pycache__/views.cpython-310.pyc
Binary file not shown.
3 changes: 3 additions & 0 deletions videotools/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions videotools/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class VideotoolsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'videotools'
Empty file.
Binary file not shown.
3 changes: 3 additions & 0 deletions videotools/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
80 changes: 80 additions & 0 deletions videotools/templates/home.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html>
<head>
<title>Upload Video</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
h1 {
margin: 0;
padding: 20px;
text-align: center;
background-color: #333;
color: #fff;
}
#upload-container {
margin: 20px auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
text-align: center;
}
label {
display: block;
margin-bottom: 10px;
font-weight: bold;
}
input[type="file"] {
display: block;
margin: 0 auto 10px;
}
button[type="submit"] {
display: block;
margin: 10px auto;
padding: 10px 20px;
background-color: #333;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
#loading {
display: none;
margin: 20px auto;
padding: 10px;
background-color: #333;
color: #fff;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Upload Videos (Mp4)</h1>

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="videos" multiple>
<button type="submit">Upload</button>
</form>

<div id="video-list">
{% if videos %}
{% for video in videos %}
<div>
<h3>{{ video.name }}</h3>
<br>
<a href="{% url 'convert_video' video.location %}" class="btn btn-primary">Convert to mp3</a>
<a href="{% url 'compress_video' video.location %}" class="btn btn-primary">Compressed</a>
</div>
{% endfor %}
{% endif %}
</div>

</body>
</html>
3 changes: 3 additions & 0 deletions videotools/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
8 changes: 8 additions & 0 deletions videotools/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.urls import path
from .views import *

urlpatterns = [
path('', upload_video, name='upload_video'),
path('convert_video/<path:video_file>/', convert_video, name='convert_video'),
path('compress_video/<path:video_file>/', compress_video, name='compress_video'),
]
62 changes: 62 additions & 0 deletions videotools/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import asyncio
import aiofiles
from django.conf import settings
from django.shortcuts import render,redirect
from django.core.files.storage import FileSystemStorage
from django.views.decorators.csrf import csrf_exempt
from django.http import FileResponse, HttpResponse, HttpResponseRedirect
from moviepy.editor import *
from urllib.parse import unquote

def upload_video(request):
if request.method == 'POST' and request.FILES.getlist('videos'):
videos = request.FILES.getlist('videos')
uploaded_videos = []

for video in videos:
fs = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, "videos/"))
filename = fs.save(video.name, video)
file_path = os.path.join("videos/",filename)
video_obj = {'name': video.name, 'url': fs.url(filename), 'location':file_path}
uploaded_videos.append(video_obj)

context = {'videos': uploaded_videos}
return render(request, 'home.html', context=context)

return render(request, 'home.html')

async def convert_video(request, video_file):
video_path = unquote(video_file)
video = VideoFileClip(video_path)
audio_file = video_path.replace('.mp4', '.mp3')
audio = video.audio
audio.write_audiofile(audio_file)
video.close()
audio.close()

async with aiofiles.open(audio_file, mode='rb') as f:
content = await f.read()

response = HttpResponse(content, content_type='audio/mpeg')
response['Content-Disposition'] = f'attachment; filename="{os.path.basename(audio_file)}"'

return response

async def compress_video(request, video_file):
video_path = unquote(video_file)
compressed_file = video_path.replace('.mp4', '_compressed.mp4')

# Build FFmpeg command string
cmd = f'ffmpeg -i "{video_path}" -codec:v libx264 -crf 28 -preset medium -b:v 200k -filter:v scale=-2:480 "{compressed_file}"'

# Run FFmpeg command asynchronously using subprocess and wait for it to complete
process = await asyncio.create_subprocess_shell(cmd)
await process.communicate()

async with aiofiles.open(compressed_file, mode='rb') as f:
content = await f.read()

response = HttpResponse(content, content_type='video/mp4')
response['Content-Disposition'] = f'attachment; filename="{os.path.basename(compressed_file)}"'

return response

0 comments on commit 593a730

Please sign in to comment.