Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,7 @@ import json
|
|
| 3 |
import uuid
|
| 4 |
import threading
|
| 5 |
import time
|
| 6 |
-
import
|
| 7 |
from io import BytesIO
|
| 8 |
from PIL import Image
|
| 9 |
from typing import Dict, Any, List, Optional
|
|
@@ -208,18 +208,40 @@ async def delete_session(session_id: str):
|
|
| 208 |
return {"status": "deleted"}
|
| 209 |
raise HTTPException(status_code=404, detail="Session not found")
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
@app.post("/split")
|
| 212 |
async def split_image(req: SplitRequest, request: Request):
|
| 213 |
if req.parts < 1 or req.parts > 20:
|
| 214 |
raise HTTPException(status_code=400, detail="Parts must be between 1 and 20")
|
| 215 |
|
| 216 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
try:
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
img = Image.open(BytesIO(
|
| 221 |
except Exception as e:
|
| 222 |
-
raise HTTPException(status_code=400, detail=f"
|
| 223 |
|
| 224 |
parts = split_image_into_parts(img, req.parts)
|
| 225 |
img_id = str(uuid.uuid4())
|
|
@@ -239,7 +261,6 @@ async def split_image(req: SplitRequest, request: Request):
|
|
| 239 |
"created": time.time()
|
| 240 |
}
|
| 241 |
|
| 242 |
-
# Генерируем полные URL
|
| 243 |
base = str(request.base_url).rstrip("/")
|
| 244 |
response_dict = {}
|
| 245 |
for i in range(1, len(parts) + 1):
|
|
|
|
| 3 |
import uuid
|
| 4 |
import threading
|
| 5 |
import time
|
| 6 |
+
import httpx
|
| 7 |
from io import BytesIO
|
| 8 |
from PIL import Image
|
| 9 |
from typing import Dict, Any, List, Optional
|
|
|
|
| 208 |
return {"status": "deleted"}
|
| 209 |
raise HTTPException(status_code=404, detail="Session not found")
|
| 210 |
|
| 211 |
+
import httpx # вместо import requests
|
| 212 |
+
|
| 213 |
+
# ... остальные импорты ...
|
| 214 |
+
|
| 215 |
+
# Конфигурация
|
| 216 |
+
MAX_IMAGE_SIZE_MB = 15 # максимальный размер скачиваемого изображения
|
| 217 |
+
|
| 218 |
@app.post("/split")
|
| 219 |
async def split_image(req: SplitRequest, request: Request):
|
| 220 |
if req.parts < 1 or req.parts > 20:
|
| 221 |
raise HTTPException(status_code=400, detail="Parts must be between 1 and 20")
|
| 222 |
|
| 223 |
+
# Асинхронная загрузка с таймаутом и лимитом размера
|
| 224 |
+
async with httpx.AsyncClient(timeout=15.0) as client:
|
| 225 |
+
try:
|
| 226 |
+
response = await client.get(req.url)
|
| 227 |
+
response.raise_for_status()
|
| 228 |
+
except httpx.TimeoutException:
|
| 229 |
+
raise HTTPException(status_code=504, detail="Image download timed out")
|
| 230 |
+
except httpx.HTTPError as e:
|
| 231 |
+
raise HTTPException(status_code=400, detail=f"Failed to fetch image: {e}")
|
| 232 |
+
|
| 233 |
+
# Проверяем размер
|
| 234 |
+
content = response.content
|
| 235 |
+
if len(content) > MAX_IMAGE_SIZE_MB * 1024 * 1024:
|
| 236 |
+
raise HTTPException(status_code=400, detail=f"Image too large (max {MAX_IMAGE_SIZE_MB} MB)")
|
| 237 |
+
|
| 238 |
+
# Обработка изображения (в синхронном режиме – PIL не асинхронный, но это быстро)
|
| 239 |
try:
|
| 240 |
+
img = Image.open(BytesIO(content))
|
| 241 |
+
img.verify() # проверяем, что это изображение
|
| 242 |
+
img = Image.open(BytesIO(content)) # переоткрываем после verify
|
| 243 |
except Exception as e:
|
| 244 |
+
raise HTTPException(status_code=400, detail=f"Invalid image: {e}")
|
| 245 |
|
| 246 |
parts = split_image_into_parts(img, req.parts)
|
| 247 |
img_id = str(uuid.uuid4())
|
|
|
|
| 261 |
"created": time.time()
|
| 262 |
}
|
| 263 |
|
|
|
|
| 264 |
base = str(request.base_url).rstrip("/")
|
| 265 |
response_dict = {}
|
| 266 |
for i in range(1, len(parts) + 1):
|