dr.botzo/dr_botzo/markov/views.py

93 lines
2.7 KiB
Python

"""Manipulate Markov data via the Django site."""
import logging
import time
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from markov.forms import LogUploadForm, TeachLineForm
import markov.lib as markovlib
from markov.models import MarkovContext
log = logging.getLogger('markov.views')
def index(request):
"""Display nothing, for the moment."""
return HttpResponse()
def context_index(request, context_id):
"""Display the context index for the given context."""
start_t = time.time()
context = get_object_or_404(MarkovContext, pk=context_id)
chain = u" ".join(markovlib.generate_line(context))
end_t = time.time()
return render(request, 'context.html', {'chain': chain,
'context': context,
'elapsed': end_t - start_t})
@permission_required('import_log_file', raise_exception=True)
def import_file(request):
"""Accept a file upload and turn it into markov stuff.
Current file formats supported:
* weechat
"""
if request.method == 'POST':
form = LogUploadForm(request.POST, request.FILES)
if form.is_valid():
log_file = request.FILES['log_file']
context = form.cleaned_data['context']
ignores = form.cleaned_data['ignore_nicks'].split(',')
strips = form.cleaned_data['strip_prefixes'].split(' ')
whos = []
for line in log_file:
(timestamp, who, what) = line.decode('utf-8').split('\t', 2)
if who in ('-->', '<--', '--', ' *'):
continue
if who in ignores:
continue
whos.append(who)
# this is a line we probably care about now
what = [x for x in what.rstrip().split(' ') if x not in strips]
markovlib.learn_line(' '.join(what), context)
log.debug(set(whos))
else:
form = LogUploadForm()
return render(request, 'import_file.html', {'form': form})
@permission_required('teach_line', raise_exception=True)
def teach_line(request):
"""Teach one line directly."""
if request.method == 'POST':
form = TeachLineForm(request.POST)
if form.is_valid():
line = form.cleaned_data['line']
context = form.cleaned_data['context']
strips = form.cleaned_data['strip_prefixes'].split(' ')
what = [x for x in line.rstrip().split(' ') if x not in strips]
markovlib.learn_line(' '.join(what), context)
else:
form = TeachLineForm()
return render(request, 'teach_line.html', {'form': form})