feat: add django-channel and daphne
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
from django.tasks import task
|
||||
from submissions.models import ImageCrop, SubmissionFile, OCRStatus
|
||||
|
||||
from PIL import Image
|
||||
import pytesseract
|
||||
|
||||
|
||||
def _process_ocr_file(file) -> bool:
|
||||
if file.ocr_status != OCRStatus.TO_PROCESS:
|
||||
return False
|
||||
|
||||
file.ocr_status = OCRStatus.PROCESSING
|
||||
file.save(update_fields=["ocr_status"])
|
||||
|
||||
try:
|
||||
file.ocr_raw_data = pytesseract.image_to_string(Image.open(file.file))
|
||||
|
||||
except Exception:
|
||||
file.ocr_status = OCRStatus.ERROR
|
||||
file.save(update_fields=["ocr_status"])
|
||||
|
||||
return False
|
||||
|
||||
finally:
|
||||
file.ocr_status = OCRStatus.PROCESSED
|
||||
file.save(update_fields=["ocr_status", "ocr_raw_data"])
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@task
|
||||
def process_submission_files():
|
||||
"""Process uploaded submission files (OCR, validation, etc.)"""
|
||||
for file in SubmissionFile.objects.filter(ocr_status=OCRStatus.TO_PROCESS):
|
||||
process_submission_file.enqueue(str(file.id))
|
||||
|
||||
|
||||
@task
|
||||
def process_submission_file(file_id: str):
|
||||
file = SubmissionFile.objects.filter(id=file_id).first()
|
||||
|
||||
if not file:
|
||||
return
|
||||
|
||||
_process_ocr_file(file)
|
||||
|
||||
process_crops.enqueue(file_id)
|
||||
|
||||
|
||||
@task
|
||||
def process_crops(file_id: str):
|
||||
file = SubmissionFile.objects.filter(id=file_id).first()
|
||||
|
||||
if not file:
|
||||
return
|
||||
|
||||
for crop in file.crops.all():
|
||||
process_crop.enqueue(str(crop.id))
|
||||
|
||||
|
||||
@task
|
||||
def process_crop(crop_id: str):
|
||||
crop = ImageCrop.objects.filter(id=crop_id).first()
|
||||
|
||||
if not crop:
|
||||
return
|
||||
|
||||
_process_ocr_file(crop)
|
||||
Reference in New Issue
Block a user