Spaces:
Sleeping
Sleeping
Download main.py from WACATW/cloud-camera: direct link, hf CLI and curl.
- Browser
- Download file 6.32 kB
-
https://huggingface.co/spaces/WACATW/cloud-camera/resolve/main/main.py
- Command line
-
hf download hf://spaces/WACATW/cloud-camera/main.py
-
curl -L -o main.py https://huggingface.co/spaces/WACATW/cloud-camera/resolve/main/main.py
6.32 kB
| """云端相机 - FastAPI 后端 | |
| 接口一览: | |
| POST /api/login 登录 / 注册(首次输入即注册) | |
| POST /api/upload 上传照片(multipart: username, pin, file) | |
| GET /api/photos 相册列表(header X-Pin 鉴权) | |
| GET /api/photo/{u}/{id} 查看图片(?t=签名令牌&thumb=1 取缩略图) | |
| DELETE /api/photo/{u}/{id} 删除照片(header X-Pin 鉴权) | |
| GET / 前端页面(同域托管 static/index.html) | |
| """ | |
| import io | |
| import time | |
| import uuid | |
| from pathlib import Path | |
| from fastapi import FastAPI, File, Form, Header, HTTPException, UploadFile | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import FileResponse | |
| from PIL import Image, UnidentifiedImageError | |
| import storage | |
| # 模块加载即确保存储目录存在(被外部应用挂载时不触发 startup 事件) | |
| storage.ensure_dirs() | |
| STATIC_DIR = Path(__file__).parent | |
| app = FastAPI(title="云端相机") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| MAX_UPLOAD_MB = 20 | |
| THUMB_MAX = 480 | |
| def _check_credentials(username: str, pin: str) -> None: | |
| if not storage.valid_username(username): | |
| raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)") | |
| if not storage.valid_pin(pin): | |
| raise HTTPException(status_code=400, detail="PIN 需为 4-20 位") | |
| if not storage.verify_user(username, pin): | |
| raise HTTPException(status_code=403, detail="用户名或 PIN 不正确") | |
| def _startup() -> None: | |
| storage.ensure_dirs() | |
| def index(): | |
| return FileResponse(str(STATIC_DIR / "index.html")) | |
| def login(payload: dict): | |
| username = str(payload.get("username", "")).strip() | |
| pin = str(payload.get("pin", "")) | |
| if not storage.valid_username(username): | |
| raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)") | |
| if not storage.valid_pin(pin): | |
| raise HTTPException(status_code=400, detail="PIN 需为 4-20 位") | |
| is_new = False | |
| if not storage.user_exists(username): | |
| storage.create_user(username, pin) | |
| is_new = True | |
| elif not storage.verify_user(username, pin): | |
| raise HTTPException(status_code=403, detail="用户名或 PIN 不正确") | |
| return {"ok": True, "is_new": is_new} | |
| async def upload( | |
| file: UploadFile = File(...), | |
| username: str = Form(...), | |
| pin: str = Form(...), | |
| ): | |
| _check_credentials(username, pin) | |
| raw = await file.read() | |
| if not raw: | |
| raise HTTPException(status_code=400, detail="文件为空") | |
| if len(raw) > MAX_UPLOAD_MB * 1024 * 1024: | |
| raise HTTPException(status_code=413, detail=f"图片超过 {MAX_UPLOAD_MB}MB 限制") | |
| try: | |
| img = Image.open(io.BytesIO(raw)) | |
| img.load() | |
| except UnidentifiedImageError: | |
| raise HTTPException(status_code=400, detail="不是有效的图片文件") | |
| except Exception: | |
| raise HTTPException(status_code=400, detail="图片解析失败") | |
| # 统一转 JPEG(含 EXIF 方向修正) | |
| img = ImageOps_exif_transpose(img) | |
| if img.mode not in ("RGB", "L"): | |
| img = img.convert("RGB") | |
| photo_id = f"{int(time.time() * 1000):x}{uuid.uuid4().hex[:6]}" | |
| user_dir = storage._user_dir(username) | |
| user_dir.mkdir(parents=True, exist_ok=True) | |
| full_path = user_dir / f"{photo_id}.jpg" | |
| img.save(full_path, "JPEG", quality=90) | |
| thumb_path = user_dir / f"{photo_id}_thumb.jpg" | |
| thumb = img.copy() | |
| thumb.thumbnail((THUMB_MAX, THUMB_MAX)) | |
| thumb.save(thumb_path, "JPEG", quality=75) | |
| photo = { | |
| "id": photo_id, | |
| "name": file.filename or f"{photo_id}.jpg", | |
| "size": len(raw), | |
| "uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"), | |
| "width": img.width, | |
| "height": img.height, | |
| } | |
| storage.add_photo(username, photo) | |
| return {"ok": True, "photo": photo} | |
| def photos(username: str, x_pin: str = Header(default="")): | |
| _check_credentials(username, x_pin) | |
| photos_list = storage.list_photos(username) | |
| for p in photos_list: | |
| pid = p["id"] | |
| p["thumb_url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}&thumb=1" | |
| p["url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}" | |
| return {"ok": True, "photos": photos_list} | |
| def photo( | |
| username: str, | |
| photo_id: str, | |
| t: str, | |
| thumb: int = 0, | |
| ): | |
| if not storage.verify_token(username, photo_id, t): | |
| raise HTTPException(status_code=403, detail="链接无效或已过期,请回到相册刷新") | |
| suffix = "_thumb" if thumb else "" | |
| path = storage._user_dir(username) / f"{photo_id}{suffix}.jpg" | |
| if not path.exists(): | |
| raise HTTPException(status_code=404, detail="照片不存在") | |
| return FileResponse(str(path), media_type="image/jpeg") | |
| def delete_photo( | |
| username: str, | |
| photo_id: str, | |
| x_pin: str = Header(default=""), | |
| ): | |
| _check_credentials(username, x_pin) | |
| if not storage.remove_photo(username, photo_id): | |
| raise HTTPException(status_code=404, detail="照片不存在") | |
| for suffix in ("", "_thumb"): | |
| p = storage._user_dir(username) / f"{photo_id}{suffix}.jpg" | |
| if p.exists(): | |
| p.unlink() | |
| return {"ok": True} | |
| def ImageOps_exif_transpose(img: Image.Image) -> Image.Image: | |
| """按 EXIF 方向信息旋转图片。""" | |
| try: | |
| exif = img.getexif() | |
| orientation = exif.get(0x0112, 1) | |
| ops = { | |
| 2: (Image.Transpose.FLIP_LEFT_RIGHT,), | |
| 3: (Image.Transpose.ROTATE_180,), | |
| 4: (Image.Transpose.FLIP_TOP_BOTTOM,), | |
| 5: (Image.Transpose.TRANSPOSE,), | |
| 6: (Image.Transpose.ROTATE_270,), | |
| 7: (Image.Transpose.TRANSVERSE,), | |
| 8: (Image.Transpose.ROTATE_90,), | |
| } | |
| for op in ops.get(orientation, ()): | |
| img = img.transpose(op) | |
| except Exception: | |
| pass | |
| return img | |