Spaces:
Sleeping
Sleeping
Download app.py from WACATW/cloud-camera: direct link, hf CLI and curl.
- Browser
- Download file 7.15 kB
-
https://huggingface.co/spaces/WACATW/cloud-camera/resolve/main/app.py
- Command line
-
hf download hf://spaces/WACATW/cloud-camera/app.py
-
curl -L -o app.py https://huggingface.co/spaces/WACATW/cloud-camera/resolve/main/app.py
7.15 kB
| """Hugging Face Space 入口(SDK: Gradio + ZeroGPU)——业务以 Gradio 原生 API 提供 | |
| ZeroGPU 平台约束(已从 spaces 库源码确认): | |
| - 必须存在 @spaces.GPU 装饰函数且必须调用 demo.launch()(spaces 的 | |
| one_launch 在 launch 时向平台注册 GPU 函数),否则报 | |
| "No @spaces.GPU function detected during startup"。 | |
| - 平台用独立实例服务 Gradio 应用,FastAPI/自定义路由无法挂载(已实测), | |
| 因此本文件把全部业务封装为 Gradio Blocks 事件(api_login / api_upload / | |
| api_photos / api_delete),前端通过 /gradio_api/call/{api_name} 调用, | |
| 照片文件通过 /gradio_api/file= 访问。 | |
| 业务事件均为普通函数(纯 CPU,不消耗 GPU 免费配额);_gpu_probe 仅为 | |
| 满足平台检测,业务从不调用。 | |
| 存储:storage.py 默认 /data(Hugging Face Space 持久化磁盘)。 | |
| """ | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| import time | |
| import uuid | |
| import gradio as gr | |
| import spaces # noqa: F401 | |
| from PIL import Image, UnidentifiedImageError | |
| import storage | |
| storage.ensure_dirs() | |
| THUMB_MAX = 480 | |
| MAX_BYTES = 20 * 1024 * 1024 | |
| def _err(msg: str) -> str: | |
| return json.dumps({"ok": False, "error": msg}, ensure_ascii=False) | |
| def _exif_transpose(img: Image.Image) -> Image.Image: | |
| 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 | |
| def api_login(username: str, pin: str) -> str: | |
| """登录 / 注册(首次输入即注册)""" | |
| username = str(username or "").strip() | |
| pin = str(pin or "") | |
| if not storage.valid_username(username): | |
| return _err("用户名不合法(1-24位,中文/字母/数字/下划线/短横线)") | |
| if not storage.valid_pin(pin): | |
| return _err("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): | |
| return _err("用户名或 PIN 不正确") | |
| return json.dumps({"ok": True, "is_new": is_new}, ensure_ascii=False) | |
| def api_upload(username: str, pin: str, file_path: str) -> str: | |
| """上传照片(file_path 为前端先经 /gradio_api/upload 得到的临时路径)""" | |
| if not storage.verify_user(username, pin): | |
| return _err("用户名或 PIN 不正确") | |
| try: | |
| with open(file_path, "rb") as f: | |
| raw = f.read() | |
| except Exception: | |
| return _err("文件读取失败,请重新上传") | |
| if not raw: | |
| return _err("文件为空") | |
| if len(raw) > MAX_BYTES: | |
| return _err("图片超过 20MB 限制") | |
| try: | |
| img = Image.open(io.BytesIO(raw)) | |
| img.load() | |
| except UnidentifiedImageError: | |
| return _err("不是有效的图片文件") | |
| except Exception: | |
| return _err("图片解析失败") | |
| img = _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) | |
| img.save(user_dir / f"{photo_id}.jpg", "JPEG", quality=90) | |
| thumb = img.copy() | |
| thumb.thumbnail((THUMB_MAX, THUMB_MAX)) | |
| thumb.save(user_dir / f"{photo_id}_thumb.jpg", "JPEG", quality=75) | |
| photo = { | |
| "id": photo_id, | |
| "name": os.path.basename(str(file_path)), | |
| "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 json.dumps({"ok": True, "photo": photo}, ensure_ascii=False) | |
| def api_photos(username: str, pin: str) -> str: | |
| """相册列表(缩略图以 base64 data URL 随列表返回,绕开 gradio file 白名单)""" | |
| if not storage.verify_user(username, pin): | |
| return _err("用户名或 PIN 不正确") | |
| user_dir = storage._user_dir(username) | |
| photos = storage.list_photos(username) | |
| for p in photos: | |
| pid = p["id"] | |
| thumb_path = user_dir / f"{pid}_thumb.jpg" | |
| if thumb_path.exists(): | |
| try: | |
| b = base64.b64encode(thumb_path.read_bytes()).decode("ascii") | |
| p["thumb_b64"] = "data:image/jpeg;base64," + b | |
| except Exception: | |
| p["thumb_b64"] = "" | |
| else: | |
| p["thumb_b64"] = "" | |
| p.pop("thumb_url", None) | |
| p.pop("url", None) | |
| return json.dumps({"ok": True, "photos": photos}, ensure_ascii=False) | |
| def api_photo(username: str, pin: str, photo_id: str) -> str: | |
| """单张原图(base64 data URL),相册查看器点开时调用""" | |
| if not storage.verify_user(username, pin): | |
| return _err("用户名或 PIN 不正确") | |
| f = storage._user_dir(username) / f"{photo_id}.jpg" | |
| if not f.exists(): | |
| return _err("照片不存在或已删除") | |
| try: | |
| b = base64.b64encode(f.read_bytes()).decode("ascii") | |
| except Exception: | |
| return _err("照片读取失败") | |
| return json.dumps({"ok": True, "b64": "data:image/jpeg;base64," + b}, ensure_ascii=False) | |
| def api_delete(username: str, pin: str, photo_id: str) -> str: | |
| """删除照片""" | |
| if not storage.verify_user(username, pin): | |
| return _err("用户名或 PIN 不正确") | |
| if not storage.remove_photo(username, photo_id): | |
| return _err("照片不存在") | |
| user_dir = storage._user_dir(username) | |
| for suffix in ("", "_thumb"): | |
| p = user_dir / f"{photo_id}{suffix}.jpg" | |
| if p.exists(): | |
| p.unlink() | |
| return json.dumps({"ok": True}, ensure_ascii=False) | |
| def _gpu_probe(): # ZeroGPU 平台检测占位函数(业务不调用) | |
| return "ok" | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 云端相机") | |
| _probe = gr.Button(visible=False) | |
| _probe.click(lambda: _gpu_probe(), outputs=None) | |
| _in_user = gr.Textbox(visible=False) | |
| _in_pin = gr.Textbox(visible=False) | |
| _in_path = gr.Textbox(visible=False) | |
| _in_photo = gr.Textbox(visible=False) | |
| _out = gr.Textbox(visible=False) | |
| gr.Button(visible=False).click(api_login, inputs=[_in_user, _in_pin], outputs=_out) | |
| gr.Button(visible=False).click(api_upload, inputs=[_in_user, _in_pin, _in_path], outputs=_out) | |
| gr.Button(visible=False).click(api_photos, inputs=[_in_user, _in_pin], outputs=_out) | |
| gr.Button(visible=False).click(api_photo, inputs=[_in_user, _in_pin, _in_photo], outputs=_out) | |
| gr.Button(visible=False).click(api_delete, inputs=[_in_user, _in_pin, _in_photo], outputs=_out) | |
| demo.queue() | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", quiet=True) | |