All pastes #762132 Raw Edit

Someone

public text v1 · immutable
·published 2007-11-05 12:26 UTC
rendered paste body
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
import os 
from align.bubu.models import RunningAlignment
from django.contrib.auth import authenticate, login, logout
from align.bubu.uuid import uuid1
from datetime import datetime

def getBasePath():
    return '/home/wojtek/Dwork/Dtest/align/bubu/media/data/'

def makeDataFile(type, uid, basepath):
    if(type == 1):
        return basepath + 'in' + uid + '.fas' 
    elif(type == 20):
        return basepath + 'out' + uid + '.fas' 
    elif(type == 21):
        return basepath + 'in' + uid + '.aln' 
    elif(type == 3):
        return basepath + 'prog' + uid + '.fas' 
    elif(type == 4):
        return basepath + 'sa' + uid + '.showalign'

def index(request):
    if not request.user.is_authenticated():
        return(startLogin(request))
    t = loader.get_template('index.html')
    c = Context({'test' : 'test text', 'username' : request.user.username})
    return HttpResponse(t.render(c))

def startProcess(algo, infile, outfile, progfile, fast):
    if(algo == 'mafft'):
        if(fast):
            os.system('mafft ' + infile + ' > ' + outfile + ' 2> ' + progfile + ' & disown')
        else:
            os.system('mafft --retree 1 ' + infile + ' > ' + outfile + ' 2> ' + progfile + ' & disown')
    else:
        if(fast):
            os.system('clustalw -infile=' + infile + ' -quicktree ' + ' > ' + progfile + ' & disown')
        else:
            os.system('clustalw -infile=' + infile + ' > ' + progfile + ' & disown')

def step1(request):
    algo = request.REQUEST['algo']
    
    # Get uuid for the communication files
    uid = uuid1().hex
    basepath = getBasePath() 
    infile = makeDataFile(1, uid, basepath)
    if(algo=='mafft'):
        outfile = makeDataFile(20, uid, basepath)
    else:
        outfile = makeDataFile(21, uid, basepath)
    progfile = makeDataFile(3, uid, basepath)
    
    # Copy the data fr4om submitted file to the alignment input file
    data = request.FILES['afile']
    infileF = open(infile, 'w')
    infileF.write(data['content'])
    infileF.close()
   
    sfile = data['filename']

    fast = False;

    try:
        fast = request.REQUEST['fast'] != None
    except:
        pass
    if(sfile.startswith("/")):
        sfile = sfile.split("/")[-1]
    else:
        sfile = sfile.split("\\")[-1]
   
    sfile = sfile.split(".")[0]
   
    # Create a new running alignment in the queue (start_date = NILL && end_date = NULL)
    ra = RunningAlignment(user_name = request.user.username,
            added_date = datetime.now(), start_date = None, end_date = None, 
            tmp_file = progfile, result_file = outfile, input_file = infile, uid = uid,
            submit_file = sfile, algo = algo)
    
    # check if there are any alignments currenlty running (start_date != NULL && end_date == NULL)
    # If no other alignments are running, start the alignment for the uploaded file.
    running = RunningAlignment.objects.filter(start_date__isnull=False, end_date__isnull=True)
    if(len(running)==0):
        ra.start_date = datetime.now()
        startProcess(algo, infile, outfile, progfile, fast)
    
    ra.save()
    
    tab = progress(request)
    tpl = loader.get_template('step1.html')
    cnt = Context({'submit' : True, 'table' : tab, 'username' : request.user.username})
    return HttpResponse(tpl.render(cnt))

def showStatus(request):
    tab = progress(request)
    tpl = loader.get_template('step1.html')
    cnt = Context({'submit' : False, 'table' : tab, 'username' : request.user.username})
    return HttpResponse(tpl.render(cnt))

def showDoc(request):
    tpl = loader.get_template('doc.html')
    cnt = Context({'username' : request.user.username})
    return HttpResponse(tpl.render(cnt))

def doDelete(request, uid):
    alignment = RunningAlignment.objects.filter(uid=uid)[0]
    if(alignment.start_date != None):
        if(alignment.algo == 'mafft'):
            os.system('pkill mafft')
            os.system('pkill disttbfast')
        else:
            os.system('pkill clustalw')
    basepath = '/home/wojtek/Dwork/Dtest/align/bubu/media/data/'
    delIfExists(makeDataFile(1, uid, basepath))
    if(alignment.algo == 'mafft'):
        delIfExists(makeDataFile(20, uid, basepath))
    else:
        delIfExists(makeDataFile(21, uid, basepath))
    delIfExists(makeDataFile(3, uid, basepath))
    alignment.delete()
    return(HttpResponse(""))

def delIfExists(filename):
    try:
        os.remove(makeDataFile(1, uid, basepath))
    except:
        pass

def getShowAlign(infile, outfile):
    os.system('showalign -sequence ' + infile + ' -outfile ' + outfile)


def progress(request):
    allrunning = RunningAlignment.objects.filter(end_date__isnull=True, start_date__isnull=False)
    if(len(allrunning) != 0):
        running = allrunning[0]
        if(running.algo == 'mafft'):
            tmpfile = open(running.tmp_file, 'r')
            tmpstr = tmpfile.read()
            tmpfile.close()
            if(tmpstr.rstrip().endswith("mafft page.")):
                running.end_date = datetime.now()
                getShowAlign(makeDataFile(20, running.uid, getBasePath()), makeDataFile(4, running.uid, getBasePath()))
                running.save()
        else:
            try:
                tmpfile = open(running.tmp_file, 'r')
                tmpstr = tmpfile.read()
                tmpfile.close()
                if(tmpstr.rfind("CLUSTAL-Alignment file created") != -1):
                    running.end_date = datetime.now()
                    getShowAlign(makeDataFile(21, running.uid, getBasePath()), makeDataFile(4, running.uid, getBasePath()))
                    running.save()
            except:
                pass

    allrunning = RunningAlignment.objects.filter(end_date__isnull=True, start_date__isnull=False)
    if(len(allrunning) == 0):
        queuedAndRunning = RunningAlignment.objects.filter(end_date__isnull=True, start_date__isnull=True).order_by('added_date')
        if(len(queuedAndRunning) != 0):
            torun = queuedAndRunning[0]
            torun.start_date = datetime.now()
            torun.save()
            os.system('mafft ' + torun.input_file + ' > ' + torun.result_file + ' 2> ' + torun.tmp_file + ' & disown')

    queuedAndRunning = RunningAlignment.objects.filter(end_date__isnull=True).order_by('-start_date', 'added_date')
   
    finished = RunningAlignment.objects.filter(end_date__isnull=False).order_by('-start_date')
   
    t = loader.get_template('progress.html')
    c = Context({'running' : queuedAndRunning, 'finished' : finished, 'username' : request.user.username})
    ret = t.render(c)
    return ret

def doProgress(request):
    return HttpResponse(progress(request))

def doFileProgress(request):
    allrunning = RunningAlignment.objects.filter(end_date__isnull=True, start_date__isnull=False)
    if(len(allrunning) != 0):
        running = allrunning[0]
        if(running.algo != 'mafft'):
            return(HttpResponse("n/a"))
        tmpfile = open(running.tmp_file, 'r')
        tmpstr = tmpfile.read()
        tmpfile.close()
        if(tmpstr.rfind("STEP")==-1):
            return(HttpResponse("0"))
        progs = tmpstr[tmpstr.rfind("STEP"):].split(" ")
        if(progs == ""):
            return(HttpResponse("0"))
        vals = filter(lambda x: x!='' and x!='STEP' and x!='f', progs)
        try:
            ret = 100*float(vals[0])/float(vals[2])
        except:
            return(HttpResponse("0"))
        return(HttpResponse(str(round(ret))))

    return(HttpResponse("0"))

def startLogin(request):
    t = loader.get_template('startLogin.html')
    c = Context()
    return HttpResponse(t.render(c))

def doLogin(request):
    user = authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        login(request, user)
        return index(request)
    else:
        return startLogin(request)

def getResultFile(request, uid):
    align = RunningAlignment.objects.filter(uid=uid)[0]
    if(align.algo == 'mafft'):
        path = makeDataFile(20, uid, '/site_media/data/')
    else:
        path = makeDataFile(21, uid, '/site_media/data/')
    return HttpResponseRedirect(path)

def getShowAlignFile(request, uid):
    return HttpResponseRedirect(makeDataFile(4, uid, '/site_media/data/'))

def doLogout(request):
    logout(request)
    return index(request)