File size: 2,634 Bytes
61c76cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb22a04
61c76cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import numpy as np
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from PIL import Image
import io
import base64

app = FastAPI(title="Upscaler API", version="2.0")

# KRITISCH: Erlaube Anfragen von deinem UI-Space
# Ersetze 'YOUR-UI-SPACE-URL' mit der URL deines UI-Spaces (z.B. 'https://your-username-upscaler-ui.hf.space')
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://astridkraft-upscaling-ui.hf.space"], 
    allow_credentials=True,
    allow_methods=["POST"],
    allow_headers=["*"],
)

def simple_upscale(image: np.ndarray, scale: float):
    height, width = image.shape[:2]
    new_width = int(width * scale)
    new_height = int(height * scale)
    return cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_CUBIC)

def upscale_image_pil(input_image: Image.Image, scale_factor: str) -> Image.Image:
    try:
        scale_float = float(scale_factor.replace('x', '').replace(',', '.'))
        img_array = np.array(input_image)
        if input_image.mode != 'RGB':
            input_image = input_image.convert('RGB')
        img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
        output = simple_upscale(img_array, scale_float)
        output_rgb = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
        return Image.fromarray(output_rgb)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Upscaling error: {str(e)}")

@app.get("/")
def read_root():
    return {"message": "Upscaler API is running", "endpoint": "/upscale"}

@app.post("/upscale")
async def api_upscale(file: UploadFile = File(...), scale: str = Form("4x")):
    try:
        contents = await file.read()
        image = Image.open(io.BytesIO(contents))
        upscaled = upscale_image_pil(image, scale)
        
        output_buffer = io.BytesIO()
        upscaled.save(output_buffer, format="PNG")
        output_buffer.seek(0)
        
        base64_image = base64.b64encode(output_buffer.getvalue()).decode('utf-8')
        
        return JSONResponse({
            "success": True,
            "original_size": {"width": image.width, "height": image.height},
            "upscaled_size": {"width": upscaled.width, "height": upscaled.height},
            "scale_factor": scale,
            "image_base64": f"data:image/png;base64,{base64_image}"
        })
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Server error: {str(e)}")

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