Astridkraft commited on
Commit
61c76cd
·
verified ·
1 Parent(s): 49d7f40

Create api.py

Browse files
Files changed (1) hide show
  1. api.py +70 -0
api.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from fastapi.responses import JSONResponse
6
+ from PIL import Image
7
+ import io
8
+ import base64
9
+
10
+ app = FastAPI(title="Upscaler API", version="2.0")
11
+
12
+ # KRITISCH: Erlaube Anfragen von deinem UI-Space
13
+ # Ersetze 'YOUR-UI-SPACE-URL' mit der URL deines UI-Spaces (z.B. 'https://your-username-upscaler-ui.hf.space')
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["https://huggingface.co/spaces/Astridkraft/upscaling-ui"],
17
+ allow_credentials=True,
18
+ allow_methods=["POST"],
19
+ allow_headers=["*"],
20
+ )
21
+
22
+ def simple_upscale(image: np.ndarray, scale: float):
23
+ height, width = image.shape[:2]
24
+ new_width = int(width * scale)
25
+ new_height = int(height * scale)
26
+ return cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_CUBIC)
27
+
28
+ def upscale_image_pil(input_image: Image.Image, scale_factor: str) -> Image.Image:
29
+ try:
30
+ scale_float = float(scale_factor.replace('x', '').replace(',', '.'))
31
+ img_array = np.array(input_image)
32
+ if input_image.mode != 'RGB':
33
+ input_image = input_image.convert('RGB')
34
+ img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
35
+ output = simple_upscale(img_array, scale_float)
36
+ output_rgb = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
37
+ return Image.fromarray(output_rgb)
38
+ except Exception as e:
39
+ raise HTTPException(status_code=500, detail=f"Upscaling error: {str(e)}")
40
+
41
+ @app.get("/")
42
+ def read_root():
43
+ return {"message": "Upscaler API is running", "endpoint": "/upscale"}
44
+
45
+ @app.post("/upscale")
46
+ async def api_upscale(file: UploadFile = File(...), scale: str = Form("4x")):
47
+ try:
48
+ contents = await file.read()
49
+ image = Image.open(io.BytesIO(contents))
50
+ upscaled = upscale_image_pil(image, scale)
51
+
52
+ output_buffer = io.BytesIO()
53
+ upscaled.save(output_buffer, format="PNG")
54
+ output_buffer.seek(0)
55
+
56
+ base64_image = base64.b64encode(output_buffer.getvalue()).decode('utf-8')
57
+
58
+ return JSONResponse({
59
+ "success": True,
60
+ "original_size": {"width": image.width, "height": image.height},
61
+ "upscaled_size": {"width": upscaled.width, "height": upscaled.height},
62
+ "scale_factor": scale,
63
+ "image_base64": f"data:image/png;base64,{base64_image}"
64
+ })
65
+ except Exception as e:
66
+ raise HTTPException(status_code=500, detail=f"Server error: {str(e)}")
67
+
68
+ if __name__ == "__main__":
69
+ import uvicorn
70
+ uvicorn.run(app, host="0.0.0.0", port=7860)