Example #1
0
def start(request):
    global Big_Matrix
    if not request.user.is_authenticated():
        return redirect(reverse('registration_register'))
    # if 'version' in request.session:
    #     version = request.session['version']
    # else:
    try:
        version = Version.objects.order_by('-id')[0]
    except IndexError:
        version = Version(date=datetime.datetime.now())
        version.save()
    rnd = Round(version=version, user=request.user, date=datetime.datetime.now())
    rnd.save()
    products = Product.objects.filter(selectable=True)
    (a, b, c) = random.sample(products, 3)
    poll = Poll(round=rnd, product_a=a, product_b=b, product_c=c, date=datetime.datetime.now())

    #	(a,b,c)=get_meals(Big_Matrix, [])
    #	poll = Poll(round=rnd, product_a=Product.objects.get(stimuliNum = a, version = version), product_b=Product.objects.get(stimuliNum = b, version = version), product_c=Product.objects.get(stimuliNum = c, version = version), date=datetime.datetime.now())

    poll.save()
    #	(a,b,c)=get_meals(BigMatrix.objects.get(version = version).matrix, [])#bad_functions)
    #	poll = Poll(round=rnd, product_a=Product.objects.get(oid = a, version = version), product_b=Product.objects.get(oid = b, version = version), product_c=Product.objects.get(oid = c, version = version), date=datetime.datetime.now())
    #	poll.save()
    return redirect('/preferences')
Example #2
0
def set_version(request, version_id):
	try:
		version = Version.objects.get(id=version_id)
	except Version.DoesNotExist:
		return redirect('/')
	request.session['version']= version
	return redirect('/')
Example #3
0
def login(request):
	user = User()
	if request.method == 'GET':
		if 'login-user' in request.session:
			user = request.session['login-user']
		return render(request, 'login.html', {'user':user})
	if request.method == "POST":
		try:
			user = User.objects.get(email=request.POST['email'],
					password=hashlib.sha1(request.POST['password']).hexdigest())
		except:
			pass
	if not user.id:
		user.email = request.POST['email']
		user.errors = ['invalid-login']
		request.session['login-user'] = user
		return redirect('/login')
	user.last_login = datetime.datetime.now()
	user.save()
	request.session["USER_ID"] = user.id
	if 'login-user' in request.session:
		del request.session['login-user']
	if 'version' in request.session:
		del request.session['version']
	return redirect('/')
Example #4
0
def preferences(request):
	try:
		rnd = Round.objects.filter(user=request.user).order_by('-id')[0]
	except IndexError:
		return redirect('/')
	polls = Poll.objects.select_related().filter(round=rnd).order_by('-id')
	if not polls:
		return redirect('/start')
	poll = polls[0]
	return render(request, 'preferences.html', {'poll':poll})
Example #5
0
def main(request):
    if not request.user.is_authenticated():
        return redirect(reverse('registration_register'))
    # if 'version' in request.session:
    #     version = request.session['version']
    #     print "Taking Version from Session"
    # else:
    #     print "Taking Version from DB"
    try:
        version = Version.objects.filter()[0]
    except IndexError:
        version = Version(date=datetime.datetime.now())
        version.save()
    a = [[], [], [], []]
    if version:
        products = Product.objects.filter(version=version, selectable=True)
        for i in range(products.count() / 4):
            a[0].append(products[4 * i])
            a[1].append(products[4 * i + 1])
            a[2].append(products[4 * i + 2])
            a[3].append(products[4 * i + 3])
    products = a
    # global Big_Matrix
    # Big_Matrix = eval(BigMatrix.objects.get(version = version).matrix)
    # Big_Matrix = dpt2Matrix.Big_Matrix
    # changing to custom page to test- change from main.html to dinestart.html
    return render(request, 'main.html', {'products': products, 'version': version})
Example #6
0
def signup(request):
	if 'signin-user' in request.session:
		user = request.session['signin-user']
	else:
		user = User()
	if request.method == 'GET':
		return render(request, 'signup.html', {'user':user})
	if request.method == 'POST':
		user.errors = []
		user.email = request.POST['email']
		user.first_name = request.POST['first_name']
		user.last_name = request.POST['last_name']
		user.password = request.POST['password']
		user.password2 = request.POST['password2']
		if not user.email:
			user.errors.append('blank-email')
		else:
			if not email_re.match(user.email):
				user.errors.append('invalid-email')
			elif User.objects.filter(email=user.email):
				user.errors.append('email-exists')
		if not user.password:
			user.errors.append('blank-password')
		elif user.password != user.password2:
			user.errors.append('passwords-dont-match')
		if user.errors:
			request.session['signin-user'] = user
			return redirect('/signup')
		if 'signin-user' in request.session:
			del request.session['signin-user']
		user.date_joined = datetime.datetime.now()
		user.last_login = datetime.datetime.now()
		user.password = hashlib.sha1(user.password).hexdigest()
		if user.email in settings.ADMINS:
			user.admin = True
		if request.user.guest:
			user.id = request.user.id
		user.save()
		request.session['USER_ID'] = user.id
		if 'version' in request.session:
			del request.session['version']
		return redirect('/')
Example #7
0
def start(request):
	if 'version' in request.session:
		version = request.session['version']
	else:
		try:
			version = Version.objects.order_by('-id')[0]
		except IndexError:
			return redirect('/')
	if not request.user.id:
		user = User(guest=True, date_joined=datetime.datetime.now(), last_login=datetime.datetime.now())
		user.save()
		request.session["USER_ID"] = user.id
		return redirect('/start')
	rnd = Round(version=version, user=request.user, date=datetime.datetime.now())
	rnd.save()
	products = Product.objects.filter(version=version, selectable=True)
	a, b, c = random.sample(products, 3)
	poll = Poll(round=rnd, product_a=a, product_b=b, product_c=c, date=datetime.datetime.now())
	poll.save()
	return redirect('/preferences')
Example #8
0
def random_meal(request):  #reinier
    # if 'version' in request.session:
    #     version = request.session['version']
    # else:
    try:
        version = Version.objects.order_by('-id')[0]
    except IndexError:
        return redirect('/')
    products = Product.objects.filter(version=version)
    output = len(products)
    random_num = random.randint(1, len(products) - 1)
    meal = products[random_num]
    return render(request, 'random_meal.html', {'versions': versions, 'output': output, 'meal': meal})
Example #9
0
def results(request, page=None):
	if 'version' in request.session:
		version = request.session['version']
	else:
		try:
			version = Version.objects.order_by('-id')[0]
		except IndexError:
			return redirect('/')
	rnd = Round.objects.filter(user=request.user).order_by('-id')[0]
	results = Result.objects.filter(round=rnd)

	property_ids = [x.id for x in Property.objects.filter(version=version)]
	function_ids = [r.function_id for r in results]
	function_properties = FunctionProperty.objects.select_related().filter(function__id__in=function_ids).values_list('function_id', 'property_id', 'value')
	properties = {}
	for p in property_ids:
		properties[p] = 0
	for p in function_properties:
		properties[p[1]] += p[2]
	for i in properties.keys():
		properties[i] /= len(function_ids)

	products = Product.objects.filter(version=version)
	product_properties = ProductProperty.objects.select_related().filter(product__in=products).values_list('product_id', 'property_id', 'value')
	p_coefficients = {}
	for p in products:
		p_coefficients[p.id] = {}
	for c in product_properties:
		p_coefficients[c[0]][c[1]] = c[2]

	products = products.values()
	for product in products:
		score = 0
		for property_id in property_ids:
			score += properties[property_id] * p_coefficients[product['id']][property_id]
		product['score'] = score
	products = sorted(products, key=lambda k: k['score'])
	products.reverse()

	pages = []
	for i in range(len(products) / 8):
		pages.append(products[8 * i:8 * i + 8])

	products = products[:8]

	polls = Poll.objects.filter(round=rnd)
	return render(request, 'results.html', {'results':results, 'products':products, 'polls':polls, 'pages':pages})
Example #10
0
def choose(request):
	if 'version' in request.session:
		version = request.session['version']
	else:
		try:
			version = Version.objects.order_by('-id')[0]
		except IndexError:
			return redirect('/')
	rnd = Round.objects.filter(user=request.user).order_by('-id')[0]
	polls = [p for p in Poll.objects.select_related().filter(round=rnd).order_by('-id')]
	if not polls:
		return redirect('/start')
	poll = polls[0]
	poll.choice = Product.objects.get(id=request.POST['id'])
	poll.save()

	polls.reverse()
	choices = []
	ordered_choices = []
	for poll in polls:
		for p in [poll.product_a,poll.product_b,poll.product_c]:
			if not p in choices:
				choices.append(p)
		not_selected = [p for p in [poll.product_a,poll.product_b,poll.product_c] if p != poll.choice]
		ordered_choices.append([poll.choice, not_selected[0]])
		ordered_choices.append([poll.choice, not_selected[1]])

	property_ids = [x.id for x in Property.objects.filter(version=version)]
	function_ids = [f.id for f in Function.objects.filter(version=version)]
	function_properties = FunctionProperty.objects.select_related().filter(function__id__in=function_ids).values_list('function_id', 'property_id', 'value')
	f_properties = {}
	for fid in function_ids:
		f_properties[fid] = {}
	for p in function_properties:
		f_properties[p[0]][p[1]] = p[2]

	product_properties = ProductProperty.objects.select_related().filter(product__in=choices).values_list('product_id', 'property_id', 'value')
	p_coefficients = {}
	for p in choices:
		p_coefficients[p.id] = {}
	for c in product_properties:
		p_coefficients[c[0]][c[1]] = c[2]

	last_bad_functions = []
	bad_functions = []

	for listing in ordered_choices:
		print listing
		if len(ordered_choices) > 2 and listing == ordered_choices[-2]:
			last_bad_functions = [x for x in bad_functions]
		for function_id in function_ids:
			score_listing = []
			for product in listing:
				score = 0
				for property_id in property_ids:
					score += f_properties[function_id][property_id] * p_coefficients[product.id][property_id]
				score_listing.append(score)
			if score_listing[0] < score_listing[1]:
				if not function_id in bad_functions:
					bad_functions.append(function_id)
	finals = []
	if len(function_ids) - len(bad_functions) == 1:
		finals = [f for f in function_ids if f not in bad_functions]
	if len(function_ids) == len(bad_functions):
		finals = [f for f in function_ids if f not in last_bad_functions]
	if finals:
		for final in finals:
			result = Result(round=rnd,function_id=final)
			result.save()
		return redirect('/results')
	used = []
	for poll in polls:
		used.append(poll.product_a)
		used.append(poll.product_b)
		used.append(poll.product_c)
	products = [p for p in Product.objects.filter(version=version, selectable=True) if p not in used]
	a, b, c = random.sample(products, 3)
	poll = Poll(round=rnd, product_a=a, product_b=b, product_c=c, date=datetime.datetime.now())
	poll.save()
	return redirect('/preferences')
Example #11
0
def logout(request):
	if "USER_ID" in request.session:
		del request.session["USER_ID"]
	if 'version' in request.session:
		del request.session['version']
	return redirect('/')
Example #12
0
def my_foodie(request):  #reinier
    return redirect('/login')
Example #13
0
def results(request, page=None):
    # if 'version' in request.session:
    #     version = request.session['version']
    # else:
    try:
        version = Version.objects.order_by('-id')[0]
    except IndexError:
        return redirect('/')
    rnd = Round.objects.filter(user=request.user).order_by('-id')[0]
    results = Result.objects.filter(round=rnd)
    property_ids = [x.id for x in Property.objects.filter(version=version)]
    function_ids = [r.function_id for r in results]
    function_properties = FunctionProperty.objects.select_related().filter(function__id__in=function_ids).values_list(
        'function_id', 'property_id', 'value')
    properties = {}
    for p in property_ids:
        properties[p] = 0

    for p in function_properties:
        try:
            properties[p[1]] += p[2]
        except KeyError:
            pass

    for i in properties.keys():
        properties[i] /= len(function_ids) or 1


    products = Product.objects.filter(version=version)
    product_properties = ProductProperty.objects.select_related().filter(product__in=products).values_list('product_id',
                                                                                                           'property_id',
                                                                                                           'value')
    p_coefficients = {}
    #print 'len products is ' + str(len(products))
    for p in products:
        p_coefficients[p.id] = {}
    #print p
    for c in product_properties:
        p_coefficients[c[0]][c[1]] = c[2]
    #print c

    allProps = Property.objects.filter(version=version)

    myStr = 'allProps is ('
    for pr in allProps:
        myStr = myStr + 'id = ' + str(pr.id) + ' & name is: ' + pr.name + ', '

    #print myStr + ')'
    products = products.values()
    for product in products:
        score = 0
        for property_id in property_ids:
            try:
                score += properties[property_id] * p_coefficients[product['id']][property_id]
            except KeyError:
                print "KeyError"
        product['score'] = score
    products = sorted(products, key=lambda k: k['score'])
    products.reverse()

    FoodVery = 0.0
    FoodSome = 0.0
    AroundVery = 0.0
    AroundSome = 0.0
    MoneyVery = 0.0
    MoneySome = 0.0
    SafetyVery = 0.0
    SafetySome = 0.0
    StressVery = 0.0
    StressSome = 0.0
    myStr = 'FinalUF is ('
    for property_id in property_ids:
        myProp = Property.objects.filter(version=version, id=property_id)
        if "Food" in myProp[0].name and "somewhat" in myProp[0].name:
            FoodSome = properties[property_id]
        if "Food" in myProp[0].name and "very" in myProp[0].name:
            FoodVery = properties[property_id]
        if "Around" in myProp[0].name and "somewhat" in myProp[0].name:
            AroundSome = properties[property_id]
        if "Around" in myProp[0].name and "very" in myProp[0].name:
            AroundVery = properties[property_id]
        if "Money" in myProp[0].name and "somewhat" in myProp[0].name:
            MoneySome = properties[property_id]
        if "Money" in myProp[0].name and "very" in myProp[0].name:
            MoneyVery = properties[property_id]
        if "Safety" in myProp[0].name and "somewhat" in myProp[0].name:
            SafetySome = properties[property_id]
        if "Safety" in myProp[0].name and "very" in myProp[0].name:
            SafetyVery = properties[property_id]
        if "Stress" in myProp[0].name and "somewhat" in myProp[0].name:
            StressSome = properties[property_id]
        if "Stress" in myProp[0].name and "very" in myProp[0].name:
            StressVery = properties[property_id]
        myStr = myStr + str(property_id) + ' = ' + str(properties[property_id]) + ', '

    print myStr + ')'

    print 'Money very: ' + str(MoneyVery)
    print 'Stress some: ' + str(StressVery)

    totalRange = 0.0
    rangeFood = max(0, FoodVery, FoodSome) - min(0, FoodVery, FoodSome)
    totalRange += rangeFood
    rangeAround = max(0, AroundVery, AroundSome) - min(0, AroundVery, AroundSome)
    totalRange += rangeAround
    rangeMoney = max(0, MoneyVery, MoneySome) - min(0, MoneyVery, MoneySome)
    totalRange += rangeMoney
    rangeSafety = max(0, SafetyVery, SafetySome) - min(0, SafetyVery, SafetySome)
    totalRange += rangeSafety
    rangeStress = max(0, StressVery, StressSome) - min(0, StressVery, StressSome)
    totalRange += rangeStress

    importances = {}
    if (FoodVery <= 0 and FoodSome <= 0) or rangeFood < (.01 * totalRange):
        importances['Food '] = 0.0
    else:
        importances['Food'] = rangeFood / totalRange
    if (AroundVery <= 0 and AroundSome <= 0) or rangeAround < (.01 * totalRange):
        importances['Getting Around '] = 0.0
    else:
        importances['Getting Around'] = rangeAround / totalRange
    if (MoneyVery <= 0 and MoneySome <= 0) or rangeMoney < (.01 * totalRange):
        importances['Money '] = 0.0
    else:
        importances['Money'] = rangeMoney / totalRange
    if (SafetyVery <= 0 and SafetySome <= 0) or rangeSafety < (.01 * totalRange):
        importances['Safety'] = 0.0
    else:
        importances['Safety'] = rangeSafety / totalRange
    if (StressVery <= 0 and StressSome <= 0) or rangeStress < (.01 * totalRange):
        importances['Stress '] = 0.0
    else:
        importances['Stress'] = rangeStress / totalRange

    importances = sorted(importances.iteritems(), key=operator.itemgetter(1), reverse=True)

    bestProduct = Product.objects.filter(version=version, oid=products[0]['oid'])

    #print bestProduct.values()

    bestProdValues = ProductProperty.objects.filter(product=bestProduct)

    #for i in range(0,4):
    #	print 'product[' + str(i) + '] is ' + products[i]['name'] + ' score is ' + str(products[i]['score'])
    #	myStr = 'product[' + str(i) + '] value is: ('
    #	for property_id in property_ids:
    #		myStr = myStr + str(p_coefficients[products[i]['id']][property_id]) + ', '
    #	print myStr + ')'

    pages = []
    for i in range(len(products) / 8):
        pages.append(products[8 * i:8 * i + 8])

    products = products[:8]

    polls = Poll.objects.filter(round=rnd)
    GraphData.objects.get_or_create(
        user=request.user,
        data=json.dumps(importances),
    )
    return render(request, 'results.html',
                  {'results': results, 'products': products, 'polls': polls, 'pages': pages, 'properties': properties,
                   'property_ids': property_ids, 'topTopic': importances[0][0], 'importances': importances})
Example #14
0
def choose(request):
    # if 'version' in request.session:
    #     version = request.session['version']
    # else:
    try:
        version = Version.objects.order_by('-id')[0]
    except IndexError:
        return redirect('/')
    rnd = Round.objects.filter(user=request.user).order_by('-id')[0]
    use_random = 1
    #print >>sys.stderr, 'at Line 260'
    polls = [p for p in Poll.objects.select_related().filter(round=rnd).order_by('-id')]
    if not polls:
        return redirect('/start')
    poll = polls[0]  # look at last poll
    poll.choice = Product.objects.get(id=request.POST['id'])  # id of product just picked
    poll.save()  # save the choices they just made

    polls.reverse()  # polls in order from oldest to newest
    choices = []  # fill with every choice that the person has made thus far
                  # (REINER-you could eliminate winners bc no more info can be gleaned
    ordered_choices = []
    for poll in polls:
        for p in [poll.product_a, poll.product_b, poll.product_c]:
            if not p in choices:
                choices.append(p)
        not_selected = [p for p in [poll.product_a, poll.product_b, poll.product_c] if p != poll.choice]
        ordered_choices.append([poll.choice, not_selected[0]])  # (one chose, one not chose)
        ordered_choices.append([poll.choice, not_selected[1]])

    property_ids = [x.id for x in Property.objects.filter(version=version)]
    function_ids = [f.id for f in Function.objects.filter(version=version)]
    function_properties = FunctionProperty.objects.select_related().filter(function__id__in=function_ids).values_list(
        'function_id', 'property_id', 'value')
    f_properties = {}
    for fid in function_ids:
        f_properties[fid] = {}  # coefficients
    for p in function_properties:
        f_properties[p[0]][p[1]] = p[2]

    product_properties = ProductProperty.objects.select_related().filter(product__in=choices).values_list('product_id',
                                                                                                          'property_id',
                                                                                                          'value')

    p_coefficients = {}
    for p in choices:
        p_coefficients[p.id] = {}
    for c in product_properties:
        p_coefficients[c[0]][c[1]] = c[2]

    last_bad_functions = []
    bad_functions = []  # go thu all UF and see if one of those pairs is violated
    ### bad functions always gets created??
    for listing in ordered_choices:
        print "listing", listing
        if len(ordered_choices) > 2 and listing == ordered_choices[-2]:
            last_bad_functions = [x for x in bad_functions]  # if every UF has been violated then revert to last state
        for function_id in function_ids:
            score_listing = []
            for product in listing:
                score = 0
                for property_id in property_ids:
                    try:
                        score += f_properties[function_id][property_id] * p_coefficients[product.id][property_id]
                    except (KeyError, AttributeError):
                        print "KeyError"
                score_listing.append(score)
            if score_listing[0] < score_listing[1]:
                if not function_id in bad_functions:
                    bad_functions.append(function_id)
                ## Work on before
                ## Transitiv

    #print >>sys.stderr, 'at Line 316'
    finals = []
    print function_ids, bad_functions, last_bad_functions
    if len(function_ids) - len(bad_functions) == 1:
        finals = [f for f in function_ids if f not in bad_functions]
        print finals
    if len(function_ids) == len(bad_functions):
        finals = [f for f in function_ids if f not in last_bad_functions]
        print finals
    if len(bad_functions) == len(last_bad_functions):
        finals = [f for f in function_ids if f not in last_bad_functions]
        print finals
    if finals:
        for final in finals:
            result = Result(round=rnd, function_id=final)
            result.save()
        return redirect('/results')
    else:
        print "No finals"

    if use_random == 1:
        used = []
        for poll in polls:
            used.append(poll.product_a)
            used.append(poll.product_b)
            used.append(poll.product_c)
        products = [p for p in Product.objects.filter(version=version, selectable=True) if p not in used]
        if len(products) < 3:
            products = Product.objects.filter(version=version, selectable=True)
        (a, b, c) = random.sample(products, 3)
        poll = Poll(round=rnd, product_a=a, product_b=b, product_c=c, date=datetime.datetime.now())
        poll.save()
    else:
        global Big_Matrix
        (a, b, c) = get_meals(Big_Matrix, bad_functions)
        #print 'a is' + str(a)
        #print 'b is' + str(b)
        #print 'c is' + str(c)

        poll = Poll(round=rnd, product_a=Product.objects.get(stimuliNum=a, version=version),
                    product_b=Product.objects.get(stimuliNum=b, version=version),
                    product_c=Product.objects.get(stimuliNum=c, version=version), date=datetime.datetime.now())
        poll.save()

    #print >>sys.stderr, 'Before getMeals'


    return redirect('/preferences')
Example #15
0
def main(request):
	if request.method == 'GET':
		return render(request, 'import.html', {})
	if request.method == 'POST':
		if not 'file' in request.FILES:
			return redirect('/import')
		fh, filename = tempfile.mkstemp()
		for chunk in request.FILES['file'].chunks():
			os.write(fh, chunk)
		try:
			workbook = xlrd.open_workbook(filename)
		except:
			return redirect('/import')
		if workbook.sheet_by_index(0).ncols != workbook.sheet_by_index(1).ncols + 2:
			return redirect('/import')
		sheet = workbook.sheet_by_index(0)
		for row in range(1, sheet.nrows):
			if not sheet.cell(row, 2).value:
				return redirect('/import1')
			try:
				x = int(sheet.cell(row, 1).value)
			except:
				return redirect('/import2')
			for col in range(3, sheet.ncols):
				try:
					x = float(sheet.cell(row, col).value)
				except:
					return redirect('/import3')
		sheet = workbook.sheet_by_index(1)
		for row in range(1, sheet.nrows):
			try:
				x = int(sheet.cell(row, 1).value)
			except:
				return redirect('/import4')
			for col in range(1, sheet.ncols):
				try:
					x = float(sheet.cell(row, col).value)
				except:
					return redirect('/import5')
		version = Version()
		version.save()
		destpath = os.path.join(settings.DATA_ROOT, 'images', str(version.id))
		if os.path.isdir(destpath):
			shutil.rmtree(destpath)
		os.mkdir(destpath)
		properties = []
		sheet = workbook.sheet_by_index(0)
		for col in range(3, sheet.ncols):
			property = Property(version=version, name=sheet.cell(0, col).value)
			property.save()
			properties.append(property)
		for row in range(1, sheet.nrows):
			product = Product(version=version, oid=sheet.cell(row, 1).value, name=sheet.cell(row, 2).value)
			if sheet.cell(row, 0).value:
				product.selectable = True
			else:
				product.selectable = False
			product.save()
			for col in range(3, sheet.ncols):
				product_property = ProductProperty(product=product,
						property=properties[col - 3],
						value=sheet.cell(row, col).value)
				product_property.save()
		sheet = workbook.sheet_by_index(1)
		for row in range(1, sheet.nrows):
			function = Function(version=version, oid=sheet.cell(row, 0).value)
			function.save()
			for col in range(1, sheet.ncols):
				function_property = FunctionProperty(function=function,
						property=properties[col - 1],
						value=sheet.cell(row, col).value)
				function_property.save()
		for product in Product.objects.filter(version=version, selectable=True):
			srcpath = os.path.join(settings.DROPBOX_ROOT, 'products')
			for f in os.listdir(srcpath):
				if f.startswith('%s-'%product.oid):
					im = Image.open(os.path.join(srcpath, f))
					im2 = im.copy()
					im2.thumbnail((200, 350), Image.ANTIALIAS)
					im2.save('%s/%s.png'%(destpath, product.oid), 'PNG')
					im2 = im.copy()
					im2.thumbnail((140, 245), Image.ANTIALIAS)
					im2.save('%s/%st.png'%(destpath, product.oid), 'PNG')
			srcpath = os.path.join(settings.DROPBOX_ROOT, 'products-data')
			for f in os.listdir(srcpath):
				if f.startswith('%s-'%product.oid):
					im = Image.open(os.path.join(srcpath, f))
					im2 = im.copy()
					im2.thumbnail((267, 219), Image.ANTIALIAS)
					im2.save('%s/%sd.png'%(destpath, product.oid), 'PNG')
		srcpath = os.path.join(settings.DROPBOX_ROOT, 'results')
		for product in Product.objects.filter(version=version):
			for f in os.listdir(srcpath):
				if f.startswith('%s-'%product.oid):
					im = Image.open(os.path.join(srcpath, f))
					im2 = im.copy()
					im2.thumbnail((100, 100), Image.ANTIALIAS)
					im2.save('%s/%sr.png'%(destpath, product.oid), 'PNG')
	return redirect('/')
Example #16
0
def main(request):
    if request.method == 'GET':
        return render(request, 'import.html', {})
    if request.method == 'POST':
        rowStart = 8
        if not 'file' in request.FILES:
            return redirect('/import')
        fh, filename = tempfile.mkstemp()
        for chunk in request.FILES['file'].chunks():
            os.write(fh, chunk)
        try:
            workbook = xlrd.open_workbook(filename)
        except:
            return redirect('/import')
        #if workbook.sheet_by_index(0).ncols != workbook.sheet_by_index(1).ncols + 2:
        #return redirect('/import')
        sheet = workbook.sheet_by_index(0) # Was intially index(0)
        for i in range(rowStart, sheet.ncols):#sheet.nrows):
            if sheet.cell(rowStart, i).value == "STOP":
                ncolumns = i
                #return redirect('/')
                break

        for i in range(ncolumns, sheet.ncols):
            if sheet.cell(rowStart, i).value == "STOP2":
                ncolumns_util = i
                break
            #return HttpResponse(sheet.cell(rowStart, ncolumns_util))

    for row in range(rowStart + 1, sheet.nrows):
        try:
            x = int(sheet.cell(row, ncolumns + 1).value)
        except:
            return redirect('/import4')
        for col in range(ncolumns + 1, ncolumns_util): # Was intially sheet.ncols
            try:
                x = float(sheet.cell(row, col).value)
            except:
                return redirect('/import5')
        version = Version()
        version.save()
        #return HttpResponse("Reached 67")
        #For images
        #		destpath = os.path.join(settings.DATA_ROOT, 'images', str(version.id))
        #		if os.path.isdir(destpath):
        #			shutil.rmtree(destpath)
        #		os.mkdir(destpath)
        properties = []
        #sheet = workbook.sheet_by_index(1) # Was index(1)
        for col in range(7, ncolumns):  # Was (3, sheet.ncols)
            property = Property(version=version, name=sheet.cell(rowStart, col).value) ## was (0
            property.save()
            properties.append(property)
        #return HttpResponse(properties[0].name)
        #-----------------------------------------------------------------------------------------------------
        # Restaurant DATA
        sheet = workbook.sheet_by_index(1)
        for row in range(9, sheet.nrows):
            restaurant = Restaurant(version=version, oid=sheet.cell(row, 0).value, name=sheet.cell(row, 1).value,
                                    link=sheet.cell(row, 2).value)#,menu=sheet.cell(row,6))
            restaurant.save()

        sheet = workbook.sheet_by_index(0)
        for row in range(rowStart + 1, sheet.nrows):
            #print >>sys.stderr, 'version is ' + str(version.id) + ' row is ' + str(row) + ' nrows is ' + str(sheet.nrows)
            product = Product(version=version, oid=sheet.cell(row, 1).value, name=sheet.cell(row, 2).value,
                              restaurant=Restaurant.objects.get(oid=sheet.cell(row, 3).value,
                                                                version=version))#get(oid=sheet.cell(row, 3).value))
            if sheet.cell(row, 0).value:
                product.selectable = True
                product.stimuliNum = oid = sheet.cell(row, 0).value
            else:
                product.selectable = False
            if sheet.cell(row, 5).value == 1: #AC
                product.gem = True
            else:
                product.gem = False
            product.save()
            for col in range(7, ncolumns):
                product_property = ProductProperty(product=product,
                                                   property=properties[col - 7],
                                                   value=sheet.cell(row, col).value)
                product_property.save()

            #		sheet = workbook.sheet_by_index(0)
        for row in range(rowStart + 1, sheet.nrows):
            function = Function(version=version, oid=sheet.cell(row, 1).value)
            function.save()
            for col in range(ncolumns + 1, ncolumns_util):
                function_property = FunctionProperty(function=function, property=properties[col - (ncolumns + 1)],
                                                     value=sheet.cell(row, col).value)
                function_property.save()
            #	return redirect('/')

            ### Import Images ### ### IMPORTANT, once stimuli are up!!! ###
            #		for product in Product.objects.filter(version=version, selectable=True):
            #			srcpath = os.path.join(settings.DROPBOX_ROOT)#, 'products')
            #			for f in os.listdir(srcpath):
            #				if f.startswith('%s-'%product.oid):
            #					im = Image.open(os.path.join(srcpath, f))
            #					im2 = im.copy()
            #					im2 = im2.convert('RGB')
            ###					im2.thumbnail((200, 350), Image.ANTIALIAS)
            #					im2.save('%s/%s.png'%(destpath, product.oid), 'PNG')
            ###					im2 = im.copy()
            ###					im2.thumbnail((140, 245), Image.ANTIALIAS)
            ###					im2.save('%s/%st.png'%(destpath, product.oid), 'PNG')
            ###			srcpath = os.path.join(settings.DROPBOX_ROOT, 'products-data')
            ###			for f in os.listdir(srcpath):
            ###				if f.startswith('%s-'%product.oid):
            ###					im = Image.open(os.path.join(srcpath, f))
            ###					im2 = im.copy()
            ###					im2.thumbnail((267, 219), Image.ANTIALIAS)
            ###					im2.save('%s/%sd.png'%(destpath, product.oid), 'PNG')
            ###		srcpath = os.path.join(settings.DROPBOX_ROOT, 'results')
            ###		for product in Product.objects.filter(version=version):
            ###			for f in os.listdir(srcpath):
            ###				if f.startswith('%s-'%product.oid):
            ###					im = Image.open(os.path.join(srcpath, f))
            ###					im2 = im.copy()
            ###					im2.thumbnail((100, 100), Image.ANTIALIAS)
            ###					im2.save('%s/%sr.png'%(destpath, product.oid), 'PNG')
            #############################################

        ### compare pairs Matrix! ###

        index = -1
        num_stimuli = len(Product.objects.filter(version=version, selectable=True))
        num_functions = len(Function.objects.filter(version=version))
        matrix = []
        #		stimuli_col = ncolumns_util + (num_stimuli + 1)
        for i in range(ncolumns_util, sheet.ncols):
            if sheet.cell(rowStart, i).value == "STOP3":
                stimuli_col = i
                break

        for i in range(1, num_stimuli + 1): # Ranges for stimuli
            for j in range(i + 1, num_stimuli + 1):
                index += 1
                matrix.append([])
                for k in range(1, num_functions + 1):
                    matrix[index].append(int(sheet.cell(k + rowStart, stimuli_col + j).value) - int(
                        sheet.cell(k + rowStart,
                                   stimuli_col + i).value)) # Data will be coming from excel file rank(j) - rank(i)
        #matrix_Obj.save()
        f = open('dpt2Matrix.py', 'w+')
        f.write('Big_Matrix=' + str(matrix))
        f.close()

        return redirect(reverse('start'))