File size: 3,918 Bytes
a34a6d1
 
 
 
 
 
 
 
 
 
 
 
 
 
1a616a5
a34a6d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
VectorForge - Main FastAPI Application Server.
Exposes both modern REST API endpoints and Web UI for 2D character enhancement & vectorization.
"""

from pathlib import Path
import shutil
import tempfile
from typing import Optional

from fastapi import FastAPI, File, Form, UploadFile, HTTPException
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles

from engine.pipeline import ProcessingPipeline


app = FastAPI(
    title="VectorForge Engine",
    description="Hybrid 2D Art Super-Resolution & Vectorization API",
    version="1.0.0",
)

BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
TEMPLATES_DIR = BASE_DIR / "templates"
STORAGE_DIR = BASE_DIR.parent / "storage"
STORAGE_DIR.mkdir(parents=True, exist_ok=True)

# Mount static files
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")

pipeline = ProcessingPipeline(output_dir=STORAGE_DIR)


@app.get("/", response_class=HTMLResponse)
async def serve_index():
    index_file = TEMPLATES_DIR / "index.html"
    if not index_file.exists():
        raise HTTPException(status_code=404, detail="Template not found")
    return HTMLResponse(content=index_file.read_text(encoding="utf-8"))


@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "service": "VectorForge",
        "version": "1.0.0",
        "onnx_providers": pipeline.upscaler._providers,
    }


@app.post("/api/process")
async def process_image(
    file: UploadFile = File(...),
    mode: str = Form("hybrid"),
    preset: str = Form("character"),
    scale: int = Form(4),
    denoise: bool = Form(True),
):
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Uploaded file is not an image.")

    # Save uploaded file to temp path
    suffix = Path(file.filename).suffix or ".png"
    with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_input:
        shutil.copyfileobj(file.file, temp_input)
        temp_input_path = Path(temp_input.name)

    try:
        result = pipeline.process(
            input_image_path=temp_input_path,
            mode=mode,
            scale=scale,
            denoise=denoise,
            vector_preset=preset,
        )
        return {
            "job_id": result.job_id,
            "mode": result.mode,
            "original_size": result.original_size,
            "enhanced_size": result.enhanced_size,
            "original_filesize": result.original_filesize,
            "enhanced_png_filesize": result.enhanced_png_filesize,
            "svg_filesize": result.svg_filesize,
            "elapsed_seconds": result.elapsed_seconds,
            "png_url": result.png_url,
            "svg_url": result.svg_url,
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
    finally:
        if temp_input_path.exists():
            temp_input_path.unlink()


@app.get("/api/download/{job_id}/{fmt}")
async def download_file(job_id: str, fmt: str):
    fmt = fmt.lower()
    if fmt == "png":
        file_path = STORAGE_DIR / f"{job_id}_enhanced.png"
        media_type = "image/png"
        filename = f"vectorforge_{job_id}_4x.png"
    elif fmt == "svg":
        file_path = STORAGE_DIR / f"{job_id}_vector.svg"
        media_type = "image/svg+xml"
        filename = f"vectorforge_{job_id}.svg"
    else:
        raise HTTPException(status_code=400, detail="Invalid format. Supported: png, svg.")

    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Requested file not found or expired.")

    return FileResponse(
        path=str(file_path),
        media_type=media_type,
        filename=filename,
    )


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app.main:app", host="0.0.0.0", port=7860, reload=True)