from base64 import b64encode import cv2 from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.views import View from .forms import CrosswordForm from .xword import extract_crossword_grid, draw_grid class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'home/index.html', {'form': CrosswordForm()}) def post(self, request, *args, **kwargs): form = CrosswordForm(request.POST, request.FILES) if not form.is_valid(): return HttpResponseBadRequest('Invalid form data') warnings, grid, num_rows, num_cols, block_img = extract_crossword_grid( form.cleaned_data['file'].temporary_file_path(), remove_colours=False ) image = draw_grid(grid, num_rows, num_cols) _, png = cv2.imencode('.png', image) return render(request, 'home/output.html', { 'warnings': warnings, 'image_file_name': 'xword_{}.png'.format(datetime.now().strftime('%Y%m%d_%H%M%S')), 'image_url': 'data:image/png;base64,' + b64encode(png.tobytes()).decode() })