File size: 1,186 Bytes
99fdb5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# backend/workers/pdf_worker.py
import os
import uuid
import shutil

from celery_app import celery_app
from routers.pdf import (
    ghostscript_compress,
    PRESET_MAP,
    TEMP_DIR,
    safe_remove,
)

@celery_app.task(bind=True)
def pdf_compress_task(self, input_path: str, preset: str):
    output_path = None

    try:
        preset_value = PRESET_MAP.get(preset, "/screen")

        output_path = os.path.join(
            TEMP_DIR,
            f"compressed_{uuid.uuid4().hex}.pdf"
        )

        # 🔥 HEAVY WORK (Ghostscript)
        ghostscript_compress(
            input_path=input_path,
            output_path=output_path,
            preset=preset_value
        )

        if not os.path.exists(output_path):
            raise Exception("Compression failed: output file missing")

        return {
            "status": "done",
            "output_path": output_path,
            "size": os.path.getsize(output_path),
        }

    except Exception as e:
        return {
            "status": "failed",
            "error": str(e),
        }

    finally:
        # Cleanup input
        try:
            safe_remove(input_path)
        except:
            pass