Advertisement
aviksaha

Untitled

Jan 5th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.14 KB | None | 0 0
  1. from django.shortcuts import render,redirect,render_to_response
  2. import zipfile
  3. from .forms import UserRegisterForm
  4. from django.contrib import messages
  5. import urllib
  6.  
  7. from django.template import RequestContext
  8. from django.db import connection
  9. from .models import Subscription
  10. from django.contrib.auth import authenticate,login
  11. from django.contrib.auth.decorators import login_required
  12. from django.views import generic
  13. from django.views.generic import View
  14. from .forms import UserForm
  15. from django.http import HttpResponse
  16. from django.conf import settings
  17. from django.core.files.storage import FileSystemStorage
  18. import moviepy.editor as mp
  19. from shutil import make_archive
  20. import sys
  21. import timeit
  22. import cv2
  23. import argparse
  24. import os
  25. import authorize
  26. import functools
  27. from functools import cmp_to_key
  28.  
  29. from PIL import Image
  30. import urllib.request
  31. import sys
  32. import copy
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39. def resize(i,usernamec):
  40. path2 = settings.MEDIA_ROOT + "/"+usernamec+"/image/"
  41. dirs2 = os.listdir(path2)
  42. for item in dirs2:
  43. if os.path.isfile(path2 + item):
  44. im = Image.open(path2 + item)
  45. f, e = os.path.splitext(path2 + item)
  46. imResize = im.resize((1080, 720), Image.ANTIALIAS)
  47. imResize.save(path2 + str(i) + '.png', 'PNG', quality=90)
  48. i = i + 1
  49. #os.remove(path2 + item)
  50.  
  51.  
  52.  
  53.  
  54.  
  55. # Function to check if string can be cast to int
  56. def isnum(num):
  57. try:
  58. int(num)
  59. return True
  60. except:
  61. return False
  62.  
  63.  
  64. # Numerically sorts filenames
  65. def image_sort(x, y):
  66. x = int(x.split(".")[0])
  67. y = int(y.split(".")[0])
  68. return x - y
  69.  
  70. def make_video(text, ado, usernamec):
  71. fp = settings.MEDIA_ROOT + "/"+usernamec+""
  72. path = settings.MEDIA_ROOT + "/"+usernamec+"/image/"
  73. dirs = os.listdir(path)
  74. print(text)
  75. path = settings.MEDIA_ROOT + "/"+usernamec+"/image/"
  76.  
  77. resize(1,usernamec)
  78. # Construct the argument parser and parse the arguments
  79. # arg_parser = argparse.ArgumentParser()
  80. # arg_parser.add_argument("-e", "--extension", required=False, default='png',
  81. # help="Extension name. default is 'png'.")
  82. # arg_parser.add_argument("-o", "--output", required=False, default=settings.MEDIA_ROOT+"/image/", help="Output video file.")
  83. # arg_parser.add_argument("-d", "--directory", required=False, default=settings.MEDIA_ROOT+"/video/output.mp4", help="Specify image directory.")
  84. # arg_parser.add_argument("-fps", "--framerate", required=False, default='10', help="Set the video framerate.")
  85. # arg_parser.add_argument("-s", "--sort", required=False, default='numeric',
  86. # help="Determines the type of file-order sort that will be used.")
  87. # arg_parser.add_argument("-t", "--time", required=False, default='10',
  88. # help="Sets the framerate so that the video length matches the time in seconds.")
  89. # arg_parser.add_argument("-v", "--visual", required=False, default='false',
  90. # help="If 'true' then will display preview window.")
  91. # args = vars(arg_parser.parse_args())
  92.  
  93. # Arguments
  94. dir_path = settings.MEDIA_ROOT+"/"+usernamec+"/image/"
  95. ext = 'png'
  96. output = settings.MEDIA_ROOT+"/"+usernamec+"/video/output.mp4"
  97. framerate = '10'
  98. sort_type = 'numeric'
  99. time = 30
  100. visual = 'false'
  101.  
  102. # Flips 'visual' to a bool
  103. visual = visual == "true"
  104.  
  105. # Sets the framerate to argument, or defaults to 10
  106. if not isnum(framerate):
  107. framerate = 10
  108. else:
  109. framerate = int(framerate)
  110.  
  111. # Get the files from directory
  112. images2 = []
  113. images3 = []
  114. images3.append(settings.MEDIA_ROOT+"/"+usernamec+"/image/1.png")
  115. fg=0
  116. for f in os.listdir(dir_path):
  117. if fg > 0 :
  118. if f.endswith(ext):
  119. images2.append(dir_path+f)
  120. fg = fg + 1
  121.  
  122. # Sort the files found in the directory
  123.  
  124.  
  125. b = text.split(".")
  126.  
  127. # print(b[0])
  128.  
  129. h=0
  130. k=0
  131. for z in range(int(len(b))):
  132.  
  133. b[z]=b[z].replace('\r', '')
  134. b[z]=b[z].replace('\n', '')
  135. # int('avik ' + b[v])
  136. if b[z]!='':
  137. output = settings.MEDIA_ROOT+"/"+usernamec+"/video/" + str(b[z]) + ".mp4"
  138. images = []
  139.  
  140. for c in range(20):
  141. images.append(images2[k])
  142. for d in range(10):
  143. images.append(images3[0])
  144.  
  145.  
  146. print('images ' +str(len(images))+"----------"+str(len(images3)))
  147. # Determine the width and height from the first image
  148. #print(len(images))
  149. framerate = int(len(images) / int(time))
  150. print("Adjusting framerate to " + str(framerate))
  151. image_path = images[0]
  152. frame = cv2.imread(image_path)
  153.  
  154. if visual:
  155. cv2.imshow('video',frame)
  156. regular_size = os.path.getsize(image_path)
  157. height, width, channels = frame.shape
  158.  
  159. # Define the codec and create VideoWriter object
  160. fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
  161. out = cv2.VideoWriter(output, fourcc, framerate, (width, height))
  162.  
  163. for n, image in enumerate(images):
  164. image_path = image
  165. image_size = os.path.getsize(image_path)
  166. if image_size < 1:
  167. print("Cancelled: " + image)
  168. continue
  169.  
  170. frame = cv2.imread(image_path)
  171. out.write(frame) # Write out frame to video
  172. if visual:
  173. cv2.imshow('video', frame)
  174.  
  175. if (cv2.waitKey(1) & 0xFF) == ord('q'): # Hit `q` to exit
  176. break
  177. if n%100 == 0:
  178. print("Frame " + str(n))
  179.  
  180.  
  181. out.release()
  182. cv2.destroyAllWindows()
  183. print("The output video is {}".format(output))
  184.  
  185.  
  186. k=k+1
  187.  
  188. if len(b) < len(images2):
  189. if k == int(len(b)):
  190. k =0
  191. else:
  192. if k == int(len(images2)):
  193. k = 0
  194.  
  195.  
  196. path = settings.MEDIA_ROOT+"/"+usernamec+"/video/"
  197. dirs = os.listdir( path )
  198. audio = mp.AudioFileClip(settings.MEDIA_ROOT+"/"+usernamec+"/mp3/"+ado)
  199. audio2 = audio.subclip(1, 20)
  200.  
  201. for item in dirs:
  202.  
  203.  
  204. video1 = mp.VideoFileClip(path+item)
  205.  
  206.  
  207. final = video1.set_audio(audio2)
  208. final.write_videofile(settings.MEDIA_ROOT+"/allvideo/"+usernamec+"/video/"+item)
  209.  
  210. video1.reader.close()
  211. del video1.reader
  212. final.reader.close()
  213. del final.reader
  214. final.audio.reader.close_proc()
  215. del final.audio
  216.  
  217.  
  218.  
  219. os.remove(settings.MEDIA_ROOT + "/"+usernamec+"/mp3/);
  220.  
  221.  
  222.  
  223. path9 = settings.MEDIA_ROOT + "/" + usernamec + "/image/"
  224. dirs9 = os.listdir(path9)
  225.  
  226. for item in dirs9:
  227. os.remove(path9 + item);
  228. dirs9.clear()
  229. # path10 = settings.MEDIA_ROOT + "/"+usernamec+"/mp3/"
  230. # dirs10 = os.listdir(path10)
  231.  
  232. # for item in dirs10:
  233. # os.remove(path10 + item);
  234. # dirs10.clear()
  235.  
  236. path11 = settings.MEDIA_ROOT + "/"+usernamec+"/video/"
  237. dirs11 = os.listdir(path11)
  238.  
  239. for item in dirs11:
  240. os.remove(path11 + item);
  241. dirs11.clear()
  242.  
  243. if os.path.exists(settings.MEDIA_ROOT+"/allvideo/"+usernamec+".zip"):
  244. os.remove(settings.MEDIA_ROOT+"/allvideo/"+usernamec+".zip")
  245.  
  246. fantasy_zip = zipfile.ZipFile(settings.MEDIA_ROOT+"/allvideo/"+usernamec+".zip", 'w')
  247.  
  248. for folder, subfolders, files in os.walk(settings.MEDIA_ROOT+"/allvideo/"):
  249.  
  250. for file in files:
  251. if file.endswith('.mp4'):
  252. fantasy_zip.write(os.path.join(folder, file),
  253. os.path.relpath(os.path.join(folder, file), settings.MEDIA_ROOT+"/allvideo/"+usernamec),
  254. compress_type=zipfile.ZIP_DEFLATED)
  255.  
  256. fantasy_zip.close()
  257.  
  258. path14 = settings.MEDIA_ROOT + "/allvideo/" + usernamec + "/video/"
  259. dirs14 = os.listdir(path14)
  260.  
  261. for item in dirs14:
  262. os.remove(path14 + item);
  263. dirs14.clear()
  264.  
  265. path14 = settings.MEDIA_ROOT + "/allvideo/" + usernamec + "/"
  266. dirs14 = os.listdir(path14)
  267.  
  268. for item in dirs14:
  269. os.rmdir(path14 + item);
  270. dirs14.clear()
  271.  
  272.  
  273.  
  274.  
  275. posts=[
  276. {
  277. 'author':'tarek',
  278. 'date':'12-21-12'
  279. },
  280. {
  281. 'author': 'tarek2',
  282. 'date': '12-21-122'
  283. },
  284. {
  285. 'author': 'tarek3',
  286. 'date': '132-21-12'
  287. }
  288.  
  289. ]
  290. def home(request):
  291.  
  292. context={
  293. 'posts': posts,
  294. 'title': 'home'
  295. }
  296. return render(request, 'polls/home.html', context);
  297.  
  298. @login_required(redirect_field_name='admin/login')
  299. def about(request):
  300. # redirect()
  301. # fantasy_zip = zipfile.ZipFile(settings.MEDIA_ROOT+"/allvideo/tarektarek79.zip", 'w')
  302. #
  303. # for folder, subfolders, files in os.walk(settings.MEDIA_ROOT+"/allvideo/"):
  304. #
  305. # for file in files:
  306. # if file.endswith('.mp4'):
  307. # fantasy_zip.write(os.path.join(folder, file),
  308. # os.path.relpath(os.path.join(folder, file), settings.MEDIA_ROOT+"/allvideo/tarektarek79"),
  309. # compress_type=zipfile.ZIP_DEFLATED)
  310.  
  311. #fantasy_zip.close()
  312. # subinfo9 = Subscription.objects.get(user_id=request.user.id)
  313. # subinfo9.sub_value = 3
  314. # subinfo9.save()
  315. #Subscription.objects.all().delete()
  316. #
  317. # path9 = settings.MEDIA_ROOT + "/user/image/"
  318. # path10 = settings.MEDIA_ROOT + "/user/mp3/"
  319. # path11 = settings.MEDIA_ROOT + "/user/video/"
  320. # if not os.path.exists(path9) and os.path.exists(path10) and os.path.exists(path11):
  321. # os.makedirs(path9)
  322. # os.makedirs(path10)
  323. # os.makedirs(path11)
  324. #
  325. # path9 = settings.MEDIA_ROOT+"/user/image/"
  326. # dirs9 = os.listdir(path9)
  327. # for item in dirs9:
  328. # os.remove(path9 + item);
  329. # path10 = settings.MEDIA_ROOT + "/user/mp3/"
  330. # dirs10 = os.listdir(path10)
  331. # for item in dirs10:
  332. # os.remove(path10 + item);
  333. # path11 = settings.MEDIA_ROOT + "/user/video/"
  334. # dirs11 = os.listdir(path11)
  335. # for item in dirs11:
  336. # os.remove(path11 + item);
  337. # path11 = settings.MEDIA_ROOT + "/user/"
  338. # dirs11 = os.listdir(path11)
  339. # for item in dirs11:
  340. # os.rmdir(path11 + item);
  341. #os.rmdir(settings.MEDIA_ROOT + "/user/video");
  342. #os.chmod(path11, 077)
  343.  
  344. #shutil.rmtree(path11)
  345. t= Subscription.objects.filter(user_id=request.user.id)
  346. return render(request, 'polls/about.html', context={'listr':t})
  347. @login_required(redirect_field_name='admin/login')
  348. def faq(request):
  349. redirect('upload')
  350. return render(request, 'polls/faq.html')
  351. @login_required(redirect_field_name='admin/login')
  352. def news(request):
  353. return render(request, 'polls/news.html')
  354.  
  355. @login_required(redirect_field_name='next', login_url='login')
  356. def simple_upload(request):
  357. pak = Subscription.objects.get(user_id=request.user.id)
  358. sub_value= pak.sub_value
  359.  
  360. if sub_value>0:
  361. if request.method == 'POST' and request.FILES.getlist('myfile') and 'btn1' in request.POST:
  362.  
  363. txt = request.POST['test']
  364. b = txt.split(".")
  365.  
  366. a = 0
  367. for z in range(int(len(b))):
  368. b[z] = b[z].replace('\r', '')
  369. b[z] = b[z].replace('\n', '')
  370. a = a + 1
  371.  
  372.  
  373. print(a)
  374.  
  375.  
  376.  
  377. # sys.exit()
  378. ado = request.FILES['audio']
  379. ad = FileSystemStorage(location='media/'+request.user.username+'/mp3')
  380. adoname = ad.save(ado.name, ado)
  381. i = 1
  382. for afile in request.FILES.getlist('myfile'):
  383. fs = FileSystemStorage(location='media/'+request.user.username+'/image')
  384. afile.name = str(i) + ".png"
  385. filename = fs.save(afile.name, afile)
  386. uploaded_file_url = afile.name
  387. i = i + 1
  388.  
  389. if sub_value>a:
  390. path11 = settings.MEDIA_ROOT + "/" + request.user.username + "/video/"
  391. path12 = settings.MEDIA_ROOT + "/allvideo/" + request.user.username + "/video/"
  392. usernamec= request.user.username
  393. if not os.path.exists(path11) and not os.path.exists(path12):
  394. os.makedirs(path11)
  395. os.makedirs(path12)
  396. make_video(txt, adoname, usernamec)
  397. subinfo2 = Subscription.objects.get(user_id=request.user.id)
  398. sub_id = subinfo2.sub_id
  399. subinfo2.sub_value = subinfo2.sub_value - a
  400. subinfo2.save()
  401. msg2 = 'Completed'
  402. else:
  403. msg2="You don't have enough credit"
  404.  
  405. #redirect('upload')
  406.  
  407. msg20=""
  408. return render(request, 'polls/success.html', {
  409. 'msg2': msg2
  410.  
  411. })
  412. else:
  413. msg1 = 'You have no subscription or quota exceed'
  414. return render(request, 'polls/success.html', {
  415. 'msg1': msg1,
  416.  
  417. })
  418.  
  419.  
  420. if request.method == 'POST' and 'btn2' in request.POST:
  421. card = request.POST['card']
  422. authorize.Configuration.configure(
  423. authorize.Environment.TEST,
  424. '57vWge84HrX',
  425. '9ZTy3Rq3m4438L88',
  426. )
  427.  
  428. result = authorize.Recurring.create({
  429. 'amount': int(request.session['name']),
  430. 'interval_length': 1,
  431. 'interval_unit': 'months',
  432. 'credit_card': {
  433. 'card_number': card,
  434. 'expiration_date': request.POST['mm']+"-"+request.POST['yy'],
  435. 'card_code': request.POST['card_code'],
  436. },
  437. 'customer': {
  438. 'merchant_id': '657657',
  439. 'email': 'jjkjk@kjkl.com',
  440. 'description': 'UserName: '+request.user.username,
  441. },
  442.  
  443. })
  444.  
  445. print(result.subscription_id)
  446. if result.subscription_id:
  447.  
  448. subinfo2 = Subscription.objects.get(user_id=request.user.id)
  449. subinfo2.sub_id = result.subscription_id
  450. subinfo2.pack_id = request.session['name']
  451. if subinfo2.pack_id == 9:
  452. subinfo2.sub_value = 10
  453. elif subinfo2.pack_id == 99:
  454. subinfo2.sub_value = 100
  455. else:
  456. subinfo2.sub_value = 999999999
  457.  
  458. subinfo2.save()
  459. msg='SUCCESS! GO AHEAD AND START'
  460. return render(request, 'polls/success.html', {
  461. 'msg': msg,
  462.  
  463. })
  464. else:
  465. msg = 'FAILED! WRONG CARD INFO'
  466. return render(request, 'polls/success.html', {
  467. 'msg': msg,
  468.  
  469. })
  470.  
  471. subinfo = Subscription.objects.filter(user_id=request.user.id)
  472.  
  473.  
  474.  
  475. authorize.Configuration.configure(
  476. authorize.Environment.TEST,
  477. '57vWge84HrX',
  478. '9ZTy3Rq3m4438L88',
  479. )
  480.  
  481.  
  482. return render(request, 'polls/success.html',context={'subinfo':subinfo})
  483.  
  484.  
  485.  
  486. class UserFormView(View):
  487. form_class = UserForm
  488. template_name = 'polls/registration.html'
  489.  
  490. def get(self, request):
  491. form = self.form_class(None)
  492. return render(request, self.template_name, {'form': form})
  493.  
  494. def post(self, request):
  495. form = self.form_class(request.POST)
  496.  
  497. if form.is_valid():
  498. user = form.save(commit=False)
  499.  
  500. username = form.cleaned_data['username']
  501. password = form.cleaned_data['password1']
  502. user.set_password(password)
  503. user.save()
  504.  
  505. user = authenticate(username=username, password=password)
  506.  
  507. if user is not None:
  508. if user.is_active:
  509. login(request, user)
  510. sub = Subscription()
  511. sub.sub_value = 3
  512. sub.pack_id = 0
  513. sub.sub_id = 0
  514. sub.user_id = request.user.id
  515. sub.save()
  516.  
  517.  
  518.  
  519. return redirect('upload')
  520.  
  521. return render(request, self.template_name, {'form': form})
  522.  
  523.  
  524. def simple_upload2(request):
  525.  
  526. if request.method == 'POST' and request.FILES.getlist('myfile1'):
  527.  
  528. # txt = request.POST['test']
  529. #ado = request.FILES['audio']
  530. #ad = FileSystemStorage(location='media/user/mp3')
  531. #adoname = ad.save(ado.name, ado)
  532. i=1
  533. print(request.FILES.getlist('myfile1'))
  534. for afile in request.FILES.getlist('myfile1'):
  535. print(afile)
  536. fs = FileSystemStorage(location='media/test/image')
  537. afile.name = str(i) + ".png"
  538. filename = fs.save(afile.name, afile)
  539. uploaded_file_url = afile.name
  540. i = i+1
  541.  
  542.  
  543. return HttpResponse('done')
  544.  
  545. def hello(request):
  546. i= request.POST.get('i')
  547. l=9
  548.  
  549. request.session['name'] = i
  550. return HttpResponse(i)
  551. @login_required(redirect_field_name='next', login_url='admin/login')
  552. def testajax(request):
  553.  
  554. username = request.user.name
  555.  
  556. return render(request, 'polls/about.html',context={'variable': username})
  557.  
  558. def register(request):
  559. if request.method == 'POST':
  560. form = UserRegisterForm(request.POST)
  561. if form.is_valid():
  562. user = form.save()
  563. username = form.cleaned_data['username']
  564. password = form.cleaned_data['password1']
  565. user.set_password(password)
  566. user.save()
  567.  
  568. user = authenticate(username=username, password=password)
  569.  
  570. if user is not None:
  571. if user.is_active:
  572. login(request, user)
  573. sub = Subscription()
  574. sub.sub_value = 3
  575. sub.pack_id = 0
  576. sub.sub_id = 0
  577. sub.user_id = request.user.id
  578. sub.save()
  579.  
  580.  
  581.  
  582. return redirect('upload')
  583. else:
  584. form = UserRegisterForm()
  585. return render(request, 'polls/register.html', {'form': form})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement