Advertisement
Guest User

Untitled

a guest
Jun 10th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.64 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import sys, os, pexpect, subprocess, re, glob, datetime, decimal
  3. import urllib2, paramiko, uuid, os, urllib
  4. from paramiko import AuthenticationException
  5. from django.core.management import setup_environ
  6. sys.path.insert(0, os.path.realpath(os.path.dirname(__file__)))
  7. import settings
  8. setup_environ(settings)
  9. from django.template import loader, Context
  10. from encoder.models import *
  11.  
  12. def reso(w,h,nw):
  13.     nh = (nw*h)/(w*1.0)
  14.     if nh%8>=4: nh = (nh-nh%8)+8
  15.     else: nh = (nh-nh%8)
  16.     return (nw, nh)
  17.  
  18. def sftp_upload(host_name,user_name,password,remote_path,local_path):
  19.     #SFTP upload
  20.     try:
  21.         transport = paramiko.Transport((host_name, 22))
  22.         print host_name
  23.         print user_name
  24.         print password
  25.         transport.connect(username = user_name, password = password)
  26.         sftp = paramiko.SFTPClient.from_transport(transport)
  27.         sftp.put(local_path, remote_path)
  28.         sftp.close()
  29.         transport.close()
  30.     except IOError:
  31.         error_data = str(sys.exc_info()[1])
  32.         sftp.close()
  33.         transport.close()
  34.         log_conversion_error("Upload Encode to SFTP <br />" + error_data)
  35.     except AuthenticationException:
  36.         error_data = str(sys.exc_info()[1])
  37.         transport.close()
  38.         log_conversion_error("Upload Encode to SFTP <br />" + error_data)
  39.     except:
  40.         error_data = str(sys.exc_info()[1])
  41.         sftp.close()
  42.         transport.close()
  43.         print sys.exc_info()
  44.         log_conversion_error("Upload Encode to SFTP <br />" + error_data)
  45.  
  46. ffmpeg_status = subprocess.Popen("pgrep HandBrakeCLI".split(" "), stdout=subprocess.PIPE)
  47. ffmpeg_status.wait()
  48. #Make sure that ffmpeg isn't currently running
  49.  
  50.  
  51. if len(ffmpeg_status.stdout.readlines())==0:
  52.     for encoding_request in EncodingRequest.objects.filter(status=0):
  53.         print str(len(EncodingRequest.objects.filter(status=0))) + " jobs pending"
  54.         encoding_profile = EncodingProfile.objects.get(name=encoding_request.request_profile)
  55.         encoding_request.status=1
  56.         encoding_request.save()
  57.         resolution = [-1, -1]
  58.         src_ext = os.path.splitext(encoding_request.source_location)[1]
  59.         tmp_lavf_path = os.path.join("/tmp/", uuid.uuid1().hex + src_ext)
  60.         tmp_src_path = os.path.join("/tmp/", uuid.uuid1().hex + src_ext)
  61.         tmp_dst_path = os.path.join("/tmp/", uuid.uuid1().hex + ".m4v")
  62.         #Download source file to temp directory
  63.         print "Downloading File"
  64.         null_return = urllib.urlretrieve(encoding_request.source_location, tmp_lavf_path)
  65.         #lavf_conv = subprocess.Popen(str("ffmpeg -i %s -vcodec copy -acodec copy -acodec copy -f mp4 %s" % (tmp_lavf_path, tmp_src_path)).split(" "), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  66.         #null_return = lavf_conv.wait()
  67.         tmp_src_path = tmp_lavf_path
  68.         print null_return
  69.         comm_info = "mediainfo %s" % (tmp_src_path)
  70.         child = pexpect.spawn (comm_info)
  71.         raw_media_info = child.readlines()
  72.         raw_media_info = [info_line.strip("\r\n") for info_line in raw_media_info]
  73.        
  74.         try:
  75.             general_info = raw_media_info[0:raw_media_info.index("Video")]
  76.             try:
  77.                 video_info = raw_media_info[raw_media_info.index("Video"):raw_media_info.index("Audio")]
  78.             except:
  79.                 video_info = raw_media_info[raw_media_info.index("Video"):]
  80.                
  81.             for info_line in video_info:
  82.                 if info_line.split(":")[0].strip() == "Width":
  83.                     resolution[0] = int(re.search(r"([ \d]+) pixels", info_line, re.IGNORECASE).group(1).replace(" ",""))
  84.                 if info_line.split(":")[0].strip() == "Height":
  85.                     resolution[1] = int(re.search(r"([ \d]+) pixels", info_line, re.IGNORECASE).group(1).replace(" ",""))
  86.             out_height = str(reso(resolution[0], resolution[1], 640)[1])
  87.         except:
  88.             out_height = 0
  89.            
  90.         profile_context = {"source_file": tmp_src_path, "height": out_height, "output_file": tmp_dst_path, "width":encoding_profile.width}
  91.        
  92.         #comm_convert = "HandBrakeCLI -i %(source_file)s -o %(output_file)s -e x264 -b 400 -a 1 -E faac -B 112 -R 48 -6 dpl2 -f mp4 -X %(width)s -m -x level=30:cabac=0:ref=2:mixed-refs:analyse=all:me=umh:no-fast-pskip=1 -2" % profile_context
  93.         comm_convert = encoding_profile.comm_text % profile_context
  94.         print comm_convert
  95.         re_resultfilter = re.compile(r"task (?P<pass>\d) of (?P<passes>\d), (?P<progress>\d+\.\d+) %", re.IGNORECASE)
  96.         print "Converting File"
  97.         child = pexpect.spawn (comm_convert)
  98.         read_chunk = ""
  99.         fps = 0
  100.         progress = ""
  101.         while not child.eof():
  102.             read_chunk += child.read(100)
  103.             match_set = [match for match in re_resultfilter.finditer(read_chunk)]
  104.             if len(match_set)>0:
  105.                 last_match = match_set[-1]
  106.                 m_pass = float(match_set[-1].group("pass"))
  107.                 m_passes = float(match_set[-1].group("passes"))
  108.                 m_progress = float(match_set[-1].group("progress"))
  109.                 val_progress = str(round(((m_pass-1)/m_passes*100)+(m_progress/m_passes),4))
  110.                 print val_progress
  111.                 EncodingProgress.objects.create(encoding_request=encoding_request, progress=decimal.Decimal(val_progress))
  112.        
  113.         #sftp_upload(host_name,user_name,password,remote_path,local_path)
  114.         sftp_data = {}
  115.         sftp_data["host_name"] = encoding_request.destination_location.split("/")[2].split("@")[1]
  116.         sftp_data["user_name"] = encoding_request.destination_location.split("/")[2].split("@")[0].split(":")[0]
  117.         sftp_data["password"] = encoding_request.destination_location.split("/")[2].split("@")[0].split(":")[1]
  118.         sftp_data["remote_path"] = "/" + "/".join(encoding_request.destination_location.split("/")[3:])
  119.         sftp_data["local_path"] = profile_context["output_file"]
  120.         sftp_upload(**sftp_data)
  121.         notification_xml = loader.get_template("notify.xml").render(Context({"media_id":encoding_request.media_id, "task_id":465465, "destination_location":encoding_request.destination_location,"source_location":encoding_request.source_location}))
  122.         try:
  123.             null_return = urllib2.urlopen(urllib2.Request(encoding_request.notifier_uri, urllib.urlencode({"xml":notification_xml}))).read()
  124.             encoding_request.status=2
  125.         except:
  126.             encoding_request.status=3
  127.             pass            
  128.         encoding_request.save()
  129.         os.remove(profile_context["source_file"])
  130.         os.remove(profile_context["output_file"])
  131.         os.remove(tmp_lavf_path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement