ipilot7 commited on
Commit
a3f5067
·
verified ·
1 Parent(s): a3ed1c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -107
app.py CHANGED
@@ -1,116 +1,33 @@
1
- import io
2
- import os
3
- from typing import Tuple
4
-
5
  import gradio as gr
6
- from fastapi import FastAPI, UploadFile, File, HTTPException
7
- from fastapi.responses import Response, JSONResponse
8
  from PIL import Image
9
- from rembg import remove, new_session
10
-
11
- # ---- модель для удаления фона (CPU-дружелюбная) ----
12
- MODEL_NAME = os.getenv("REMBG_MODEL", "isnet-general-use")
13
- SESSION = new_session(MODEL_NAME)
14
-
15
- # ---------------- utils ----------------
16
- def _ensure_rgba(img: Image.Image) -> Image.Image:
17
- return img.convert("RGBA") if img.mode != "RGBA" else img
18
-
19
- def _remove_bg_pil(img: Image.Image) -> Image.Image:
20
- # rembg лучше кормить байтами; так стабильнее с профилями/EXIF
21
- buf = io.BytesIO()
22
- _ensure_rgba(img).save(buf, format="PNG")
23
- out = remove(buf.getvalue(), session=SESSION) # bytes PNG с альфой
24
- return Image.open(io.BytesIO(out)).convert("RGBA")
25
-
26
- def _export(image: Image.Image, fmt: str = "PNG") -> Tuple[bytes, str]:
27
- fmt = fmt.upper()
28
- bio = io.BytesIO()
29
- if fmt == "PNG":
30
- image.save(bio, format="PNG", optimize=True)
31
- return bio.getvalue(), "image/png"
32
- elif fmt == "WEBP":
33
- image.save(bio, format="WEBP", lossless=True)
34
- return bio.getvalue(), "image/webp"
35
- elif fmt in ("JPG", "JPEG"):
36
- image.convert("RGB").save(bio, format="JPEG", quality=92, optimize=True, progressive=True)
37
- return bio.getvalue(), "image/jpeg"
38
- else:
39
- raise ValueError("Unsupported format")
40
-
41
- # ---------------- FastAPI ----------------
42
- fast = FastAPI(title="Background Removal API")
43
-
44
- @fast.get("/")
45
- def root():
46
- return {
47
- "ok": True,
48
- "service": "background-removal",
49
- "model": MODEL_NAME,
50
- "endpoints": {
51
- "ui": "/",
52
- "health": "/healthz",
53
- "remove": "POST /remove-bg (multipart/form-data, field: file, optional ?fmt=png|webp|jpg)",
54
- },
55
- }
56
 
57
- @fast.get("/healthz")
58
- def healthz():
59
- return {"status": "ok", "model": MODEL_NAME}
60
 
61
- @fast.post("/remove-bg")
62
- async def remove_bg(file: UploadFile = File(...), fmt: str = "png"):
63
- if not file.content_type or not file.content_type.startswith("image/"):
64
- raise HTTPException(status_code=415, detail="expected image/*")
65
-
66
- raw = await file.read()
67
- if not raw:
68
- raise HTTPException(status_code=400, detail="empty file")
69
-
70
- try:
71
- src = Image.open(io.BytesIO(raw))
72
- except Exception as e:
73
- raise HTTPException(status_code=400, detail=f"bad image: {e}")
74
 
 
 
 
 
75
  try:
76
- cut = _remove_bg_pil(src)
77
- fmt_norm = {"png": "PNG", "webp": "WEBP", "jpg": "JPEG", "jpeg": "JPEG"}[fmt.lower()]
78
- body, media = _export(cut, fmt_norm)
79
- except KeyError:
80
- raise HTTPException(status_code=400, detail="fmt must be png|webp|jpg")
81
  except Exception as e:
82
- return JSONResponse(status_code=400, content={"ok": False, "error": str(e)})
83
-
84
- base = os.path.splitext(file.filename or "image")[0]
85
- ext = {"image/png": "png", "image/webp": "webp", "image/jpeg": "jpg"}[media]
86
- return Response(
87
- content=body,
88
- media_type=media,
89
- headers={"Content-Disposition": f'inline; filename="{base}_no_bg.{ext}"'},
90
- )
91
-
92
- # ---------------- Gradio UI ----------------
93
- def gr_remove(image: Image.Image, output_format: str):
94
- """Возвращает картинку с прозрачным фоном (или перекодированную)."""
95
- cut = _remove_bg_pil(image)
96
- if output_format == "PNG (transparent)":
97
- return cut
98
- # если пользователь хочет JPG, просто вернём как RGB (фон будет чёрный у прозрачности)
99
- if output_format == "JPG":
100
- return cut.convert("RGB")
101
- # WEBP отрендерится корректно в браузере
102
- return cut
103
-
104
- demo = gr.Interface(
105
- fn=gr_remove,
106
- inputs=[
107
- gr.Image(type="pil", label="Загрузите картинку"),
108
- gr.Dropdown(choices=["PNG (transparent)", "WEBP", "JPG"], value="PNG (transparent)", label="Формат"),
109
- ],
110
- outputs=gr.Image(type="pil", label="Результат"),
111
- title="Remove Background",
112
- description="Простой вырезатель фона. Работает в брау��ере и по API одновременно.",
113
  )
114
 
115
- # Смонтируем Gradio внутрь FastAPI: UI на "/", API-роуты живут рядом.
116
- app = gr.mount_gradio_app(fast, demo, path="/")
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import BlipProcessor, BlipForConditionalGeneration
 
3
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
6
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
 
7
 
8
+ def generate_caption(image):
9
+ # Now directly using the PIL Image object
10
+ inputs = processor(images=image, return_tensors="pt")
11
+ outputs = model.generate(**inputs)
12
+ caption = processor.decode(outputs[0], skip_special_tokens=True)
13
+ return caption
 
 
 
 
 
 
 
14
 
15
+ def caption_image(image):
16
+ """
17
+ Takes a PIL Image input and returns a caption.
18
+ """
19
  try:
20
+ caption = generate_caption(image)
21
+ return caption
 
 
 
22
  except Exception as e:
23
+ return f"An error occurred: {str(e)}"
24
+
25
+ iface = gr.Interface(
26
+ fn=caption_image,
27
+ inputs=gr.Image(type="pil"),
28
+ outputs="text",
29
+ title="Image Captioning with BLIP",
30
+ description="Upload an image to generate a caption."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  )
32
 
33
+ iface.launch().