Spaces:
Sleeping
Sleeping
File size: 2,600 Bytes
82a25a8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | import shutil
import fitz
import pytesseract
from pathlib import Path
from datetime import datetime, UTC
from pdf2image import convert_from_path
from app.core.celery_app import celery_app
from app.db.session import SessionLocal
from app.models.job import Job
from app.models.file import File
from app.services.file_downloader import (
download_file
)
from app.services.cloudinary_storage import (
upload_file
)
from app.core.config import settings
pytesseract.pytesseract.tesseract_cmd = (
shutil.which("tesseract")
or r"C:\Program Files\Tesseract-OCR\tesseract.exe"
)
@celery_app.task
def ocr_task(job_id: int):
db = SessionLocal()
job = None
try:
job = (
db.query(Job)
.filter(Job.id == job_id)
.first()
)
if not job:
return
file_id = job.options["file_id"]
language = job.options["language"]
job.status = "processing"
db.commit()
db_file = (
db.query(File)
.filter(File.id == file_id)
.first()
)
if not db_file:
raise Exception(
"File not found"
)
input_path = download_file(
db_file.s3_key
)
images = convert_from_path(
input_path,
poppler_path=settings.POPPLER_PATH
)
extracted_text = ""
for image in images:
text = pytesseract.image_to_string(
image,
lang=language
)
extracted_text += text
extracted_text += "\n\n"
output_dir = Path("outputs")
output_dir.mkdir(
parents=True,
exist_ok=True
)
output_path = (
output_dir
/
f"ocr_{job_id}.txt"
)
with open(
output_path,
"w",
encoding="utf-8"
) as f:
f.write(
extracted_text
)
cloudinary_url = upload_file(
str(output_path)
)
job.output_file_key = (
cloudinary_url
)
job.status = "completed"
job.completed_at = (
datetime.now(UTC)
)
db.commit()
except Exception as e:
print(
f"OCR Job {job_id} Failed: {e}"
)
if job:
job.status = "failed"
job.error_message = (
str(e)
)
db.commit()
finally:
db.close() |