multimodalart HF Staff commited on
Commit
78148e2
·
verified ·
1 Parent(s): 87bb010

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/cafe_interior.jpg filter=lfs diff=lfs merge=lfs -text
37
+ examples/girl_with_dog.jpg filter=lfs diff=lfs merge=lfs -text
38
+ examples/living_room_brick.jpg filter=lfs diff=lfs merge=lfs -text
39
+ examples/motorcycle_street.jpg filter=lfs diff=lfs merge=lfs -text
40
+ examples/sign_beach.jpg filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,20 @@
1
  ---
2
  title: Oasis Scene Parser
3
- emoji: 📈
4
- colorFrom: pink
5
- colorTo: blue
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.13'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
1
  ---
2
  title: Oasis Scene Parser
3
+ emoji: 🏝️
4
+ colorFrom: green
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ short_description: Photo to structured JSON scene record on CPU
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 30m
12
+ models:
13
+ - phanerozoic/oasis
14
  ---
15
 
16
+ Demo of [phanerozoic/oasis](https://huggingface.co/phanerozoic/oasis) (a finetune of
17
+ [Cactus-Compute/mirage](https://huggingface.co/Cactus-Compute/mirage), Apache-2.0). The C++17 engine is
18
+ compiled at startup and run on CPU via the authors' Python binding.
19
+
20
+ Example images from [linoyts/repo-to-space-example-inputs](https://huggingface.co/datasets/linoyts/repo-to-space-example-inputs) (CC0).
app.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Oasis scene parser: photo -> structured JSON scene record (objects, boxes, masks, OCR text, relations).
2
+
3
+ Oasis is a 2-bit CPU engine (one C++17 file). We download the engine source + weights from the model
4
+ repo, compile it once at startup with the Space's own compiler (-march=native matches the host CPU),
5
+ and call it through the authors' ctypes binding.
6
+ """
7
+ import json
8
+ import math
9
+ import os
10
+ import sys
11
+ import threading
12
+ import time
13
+
14
+
15
+ def _effective_cpus() -> int:
16
+ """CPUs we may actually use: cgroup quota (containers report the host's core count) and affinity."""
17
+ n = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 1)
18
+ try:
19
+ quota, period = open("/sys/fs/cgroup/cpu.max").read().split()[:2]
20
+ if quota != "max":
21
+ n = min(n, max(1, math.floor(int(quota) / int(period))))
22
+ except Exception:
23
+ try:
24
+ q = int(open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").read())
25
+ p = int(open("/sys/fs/cgroup/cpu/cpu.cfs_period_us").read())
26
+ if q > 0:
27
+ n = min(n, max(1, q // p))
28
+ except Exception:
29
+ pass
30
+ return n
31
+
32
+
33
+ # The engine spins its OpenMP workers; oversubscribing a CPU-limited container makes it ~15x slower.
34
+ os.environ.setdefault("OMP_NUM_THREADS", str(_effective_cpus()))
35
+
36
+ import gradio as gr
37
+ from huggingface_hub import snapshot_download
38
+ from PIL import Image, ImageDraw, ImageFont
39
+
40
+ MODEL_ID = "phanerozoic/oasis"
41
+ LANGUAGES = ["en", "de", "fr", "es", "it", "nl", "pl"]
42
+
43
+ # ---------------------------------------------------------------- engine setup
44
+ repo_dir = snapshot_download(MODEL_ID, allow_patterns=["oasis.py", "oasis.cpp", "oasis.oasis"])
45
+ build_dir = "/tmp/oasis_build"
46
+ os.makedirs(build_dir, exist_ok=True)
47
+ sys.path.insert(0, repo_dir)
48
+ import oasis as oasis_mod # noqa: E402 (authors' binding)
49
+
50
+ lib_path = os.path.join(build_dir, oasis_mod.LIBRARY)
51
+ if not os.path.isfile(lib_path):
52
+ t0 = time.time()
53
+ oasis_mod.build(out=lib_path)
54
+ print(f"[oasis] engine compiled in {time.time() - t0:.1f}s -> {lib_path}", flush=True)
55
+
56
+ MODEL = oasis_mod.Oasis(os.path.join(repo_dir, "oasis.oasis"), library=lib_path)
57
+ LOCK = threading.Lock() # one engine handle with a shared output buffer
58
+ print(f"[oasis] engine loaded, OMP_NUM_THREADS={os.environ['OMP_NUM_THREADS']} (os.cpu_count={os.cpu_count()})", flush=True)
59
+
60
+ # ---------------------------------------------------------------- drawing
61
+ PALETTE = [
62
+ (230, 25, 75), (60, 180, 75), (0, 130, 200), (245, 130, 48), (145, 30, 180),
63
+ (70, 240, 240), (240, 50, 230), (210, 245, 60), (0, 128, 128), (170, 110, 40),
64
+ ]
65
+
66
+
67
+ def _scale(pts, w, h):
68
+ return [(pts[i] * w / 1000.0, pts[i + 1] * h / 1000.0) for i in range(0, len(pts) - 1, 2)]
69
+
70
+
71
+ def _font(size):
72
+ try:
73
+ return ImageFont.truetype("DejaVuSans-Bold.ttf", size)
74
+ except Exception:
75
+ return ImageFont.load_default()
76
+
77
+
78
+ def draw_record(image: Image.Image, record: dict) -> Image.Image:
79
+ img = image.convert("RGB")
80
+ w, h = img.size
81
+ overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
82
+ od = ImageDraw.Draw(overlay)
83
+ lw = max(2, round(min(w, h) / 300))
84
+ fs = max(12, round(min(w, h) / 45))
85
+ font = _font(fs)
86
+
87
+ objects = record.get("objects") or []
88
+ for i, obj in enumerate(objects):
89
+ c = PALETTE[i % len(PALETTE)]
90
+ for poly in obj.get("mask") or []:
91
+ if isinstance(poly, list) and len(poly) >= 6 and all(isinstance(v, (int, float)) for v in poly):
92
+ od.polygon(_scale(poly, w, h), fill=c + (80,), outline=c + (220,))
93
+ img = Image.alpha_composite(img.convert("RGBA"), overlay).convert("RGB")
94
+ d = ImageDraw.Draw(img)
95
+
96
+ def label(x0, y0, text, c):
97
+ tb = d.textbbox((x0, y0), text, font=font)
98
+ y = y0 - (tb[3] - tb[1]) - 6 if y0 - (tb[3] - tb[1]) - 6 >= 0 else y0
99
+ tb = d.textbbox((x0 + 3, y + 2), text, font=font)
100
+ d.rectangle([tb[0] - 3, tb[1] - 2, tb[2] + 3, tb[3] + 2], fill=c)
101
+ d.text((x0 + 3, y + 2), text, fill=(255, 255, 255), font=font)
102
+
103
+ for i, obj in enumerate(objects):
104
+ b = obj.get("bbox")
105
+ if not b or len(b) != 4:
106
+ continue
107
+ c = PALETTE[i % len(PALETTE)]
108
+ x0, y0, x1, y1 = b[0] * w / 1000, b[1] * h / 1000, b[2] * w / 1000, b[3] * h / 1000
109
+ d.rectangle([x0, y0, x1, y1], outline=c, width=lw)
110
+ score = obj.get("score")
111
+ label(x0, y0, f"{obj.get('id', i + 1)} {obj.get('name', '?')}" + (f" {score:.2f}" if isinstance(score, (int, float)) else ""), c)
112
+
113
+ for t in record.get("text") or []:
114
+ b = t.get("bbox")
115
+ if not b or len(b) != 4:
116
+ continue
117
+ c = (255, 200, 0)
118
+ x0, y0, x1, y1 = b[0] * w / 1000, b[1] * h / 1000, b[2] * w / 1000, b[3] * h / 1000
119
+ d.rectangle([x0, y0, x1, y1], outline=c, width=lw)
120
+ label(x1 + 4, y0 + fs + 6, f"“{t.get('string', '')}”", (40, 40, 40))
121
+
122
+ # form answers that are boxes
123
+ form = record.get("form") or {}
124
+ for i, (name, field) in enumerate(form.items()):
125
+ v = field.get("value") if isinstance(field, dict) else None
126
+ if isinstance(v, list) and len(v) == 4 and all(isinstance(x, (int, float)) for x in v):
127
+ c = PALETTE[(i + 3) % len(PALETTE)]
128
+ x0, y0, x1, y1 = v[0] * w / 1000, v[1] * h / 1000, v[2] * w / 1000, v[3] * h / 1000
129
+ d.rectangle([x0, y0, x1, y1], outline=c, width=lw + 1)
130
+ label(x0, y0, name, c)
131
+ return img
132
+
133
+
134
+ def _load(image) -> Image.Image:
135
+ if image is None:
136
+ raise gr.Error("Please upload an image.")
137
+ if isinstance(image, str):
138
+ image = Image.open(image)
139
+ from PIL import ImageOps
140
+ return ImageOps.exif_transpose(image).convert("RGB")
141
+
142
+
143
+ def _run(img: Image.Image, options: dict) -> dict:
144
+ with LOCK:
145
+ try:
146
+ return MODEL.describe(img, **options)
147
+ except RuntimeError as e:
148
+ raise gr.Error(f"Oasis engine error: {e}")
149
+
150
+
151
+ # ---------------------------------------------------------------- handlers
152
+ def describe(
153
+ image,
154
+ language: str = "en",
155
+ keywords: str = "",
156
+ conf: float = 0.3,
157
+ mask_format: str = "polygons",
158
+ reasoning: bool = True,
159
+ max_objects: int = 20,
160
+ ):
161
+ """Describe a photo as a structured JSON scene record.
162
+
163
+ Args:
164
+ image: the input photo (filepath).
165
+ language: description language, one of en, de, fr, es, it, nl, pl.
166
+ keywords: optional comma-separated words to steer the description toward.
167
+ conf: object confidence threshold (0-1).
168
+ mask_format: "polygons", "largest", "merged" or "none".
169
+ reasoning: include the model's short reasoning trace.
170
+ max_objects: maximum number of objects to report.
171
+
172
+ Returns:
173
+ An annotated image (boxes, masks, read text) and the JSON scene record.
174
+ Boxes and outlines use a 0-1000 scale on each image axis.
175
+ """
176
+ img = _load(image)
177
+ options = {
178
+ "language": language,
179
+ "conf": float(conf),
180
+ "max_objects": int(max_objects),
181
+ "reasoning": bool(reasoning),
182
+ }
183
+ if mask_format == "none":
184
+ options["masks"] = False
185
+ else:
186
+ options["mask_format"] = mask_format
187
+ kw = [k.strip() for k in (keywords or "").split(",") if k.strip()]
188
+ if kw:
189
+ options["keywords"] = kw
190
+ record = _run(img, options)
191
+ return draw_record(img, record), record
192
+
193
+
194
+ DEFAULT_FORM = json.dumps(
195
+ {
196
+ "vehicle": {"enum": ["motorcycle", "bicycle", "car", "truck"]},
197
+ "color": {"enum": ["red", "blue", "black", "white"]},
198
+ "parked_cars": {"type": "integer", "minimum": 0, "maximum": 10},
199
+ "where": {"x-source": "bbox", "x-of": "vehicle"},
200
+ },
201
+ indent=2,
202
+ )
203
+
204
+
205
+ def fill_form(image, form_json: str = DEFAULT_FORM):
206
+ """Fill an ordered form about a photo.
207
+
208
+ Fields: {"name": {"enum": [...]}} for a choice, {"type": "integer", "minimum": 0, "maximum": 9} for a count,
209
+ {"type": "string"} for free text, and {"x-source": "bbox", "x-of": "<earlier choice field>"} for a box.
210
+
211
+ Args:
212
+ image: the input photo (filepath).
213
+ form_json: the form schema as JSON text.
214
+
215
+ Returns:
216
+ An annotated image (box answers drawn) and the filled form with per-answer probabilities.
217
+ """
218
+ img = _load(image)
219
+ try:
220
+ form = json.loads(form_json)
221
+ except json.JSONDecodeError as e:
222
+ raise gr.Error(f"Form is not valid JSON: {e}")
223
+ if not isinstance(form, dict) or not form:
224
+ raise gr.Error("Form must be a non-empty JSON object of fields.")
225
+ record = _run(img, {"form": form})
226
+ return draw_record(img, record), record
227
+
228
+
229
+ # ---------------------------------------------------------------- UI
230
+ CSS = """
231
+ #col-container { max-width: 1200px; margin: 0 auto; }
232
+ .dark .gradio-container { color: var(--body-text-color); }
233
+ """
234
+
235
+ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
236
+ with gr.Column(elem_id="col-container"):
237
+ gr.Markdown(
238
+ "# 🏝️ Oasis — photo → structured scene JSON\n"
239
+ "A 19 MB, 2-bit vision model (Cactus Compute's Mirage with a new CPU engine and a retrained text reader) "
240
+ "that turns a photo into a JSON record: objects with boxes and masks, text it can read, relations and a "
241
+ "short reasoning trace — or fills in a form you define. Runs on CPU. "
242
+ "[Model](https://huggingface.co/phanerozoic/oasis) · [Base model: Mirage](https://huggingface.co/Cactus-Compute/mirage)"
243
+ )
244
+ with gr.Tabs():
245
+ with gr.Tab("Describe a photo"):
246
+ with gr.Row():
247
+ with gr.Column():
248
+ d_image = gr.Image(type="filepath", label="Photo", height=420)
249
+ d_btn = gr.Button("Describe", variant="primary")
250
+ with gr.Accordion("Options", open=False):
251
+ d_lang = gr.Dropdown(LANGUAGES, value="en", label="Description language")
252
+ d_kw = gr.Textbox(label="Keywords (comma-separated, optional)", placeholder="e.g. sign, car")
253
+ d_conf = gr.Slider(0.05, 0.95, value=0.3, step=0.05, label="Object confidence threshold")
254
+ d_mask = gr.Radio(["polygons", "largest", "merged", "none"], value="polygons", label="Mask format")
255
+ d_reason = gr.Checkbox(value=True, label="Include reasoning trace")
256
+ d_maxobj = gr.Slider(1, 64, value=20, step=1, label="Max objects")
257
+ with gr.Column():
258
+ d_out_img = gr.Image(label="Annotated", height=420)
259
+ d_out_json = gr.JSON(label="Scene record")
260
+ gr.Examples(
261
+ examples=[
262
+ ["examples/sign_beach.jpg"],
263
+ ["examples/motorcycle_street.jpg"],
264
+ ["examples/girl_with_dog.jpg"],
265
+ ["examples/cafe_interior.jpg"],
266
+ ["examples/living_room_brick.jpg"],
267
+ ],
268
+ inputs=[d_image],
269
+ outputs=[d_out_img, d_out_json],
270
+ fn=describe,
271
+ cache_examples=True,
272
+ cache_mode="lazy",
273
+ )
274
+ d_btn.click(
275
+ describe,
276
+ inputs=[d_image, d_lang, d_kw, d_conf, d_mask, d_reason, d_maxobj],
277
+ outputs=[d_out_img, d_out_json],
278
+ api_name="describe",
279
+ )
280
+
281
+ with gr.Tab("Fill a form"):
282
+ with gr.Row():
283
+ with gr.Column():
284
+ f_image = gr.Image(type="filepath", label="Photo", height=420)
285
+ f_form = gr.Code(value=DEFAULT_FORM, language="json", label="Form (ordered fields)")
286
+ f_btn = gr.Button("Fill form", variant="primary")
287
+ gr.Markdown(
288
+ "Field types: `{\"enum\": [...]}` choice · `{\"type\": \"integer\", \"minimum\": 0, \"maximum\": 9}` count · "
289
+ "`{\"type\": \"string\"}` text · `{\"x-source\": \"bbox\", \"x-of\": \"<earlier choice field>\"}` box."
290
+ )
291
+ with gr.Column():
292
+ f_out_img = gr.Image(label="Annotated", height=420)
293
+ f_out_json = gr.JSON(label="Filled form")
294
+ gr.Examples(
295
+ examples=[
296
+ ["examples/motorcycle_street.jpg", DEFAULT_FORM],
297
+ [
298
+ "examples/sign_beach.jpg",
299
+ json.dumps(
300
+ {
301
+ "sign": {"enum": ["stop sign", "letter board", "billboard"]},
302
+ "place": {"enum": ["beach", "city", "forest", "kitchen"]},
303
+ "cars": {"type": "integer", "minimum": 0, "maximum": 10},
304
+ "where": {"x-source": "bbox", "x-of": "sign"},
305
+ },
306
+ indent=2,
307
+ ),
308
+ ],
309
+ [
310
+ "examples/girl_with_dog.jpg",
311
+ json.dumps(
312
+ {
313
+ "animal": {"enum": ["dog", "cat", "horse", "bird"]},
314
+ "animals": {"type": "integer", "minimum": 0, "maximum": 10},
315
+ "people": {"type": "integer", "minimum": 0, "maximum": 10},
316
+ "where": {"x-source": "bbox", "x-of": "animal"},
317
+ },
318
+ indent=2,
319
+ ),
320
+ ],
321
+ ],
322
+ inputs=[f_image, f_form],
323
+ outputs=[f_out_img, f_out_json],
324
+ fn=fill_form,
325
+ cache_examples=True,
326
+ cache_mode="lazy",
327
+ )
328
+ f_btn.click(
329
+ fill_form,
330
+ inputs=[f_image, f_form],
331
+ outputs=[f_out_img, f_out_json],
332
+ api_name="fill_form",
333
+ )
334
+
335
+ if __name__ == "__main__":
336
+ demo.launch(mcp_server=True)
examples/cafe_interior.jpg ADDED

Git LFS Details

  • SHA256: 3110d62ff20ae4ca98b3553e12e8e11ae53ffe1c4de6ac0987bb8e6ae68d337e
  • Pointer size: 131 Bytes
  • Size of remote file: 177 kB
examples/girl_with_dog.jpg ADDED

Git LFS Details

  • SHA256: cd89ec7a09a3039ca34f4c8d7a831fafd4e7a23ac8af8d2b2a330126c0e87471
  • Pointer size: 131 Bytes
  • Size of remote file: 171 kB
examples/living_room_brick.jpg ADDED

Git LFS Details

  • SHA256: f6ade748a492a801bc6487e88e06608d85039691bb697cfee086d942d54a02fb
  • Pointer size: 131 Bytes
  • Size of remote file: 137 kB
examples/motorcycle_street.jpg ADDED

Git LFS Details

  • SHA256: 03233a365e2b92d1c557bfdd5c3e3bb0b578875ba699394895899f291a6a4b13
  • Pointer size: 131 Bytes
  • Size of remote file: 182 kB
examples/sign_beach.jpg ADDED

Git LFS Details

  • SHA256: 5ca6eaefc0eb819ef45b16d915aaf9d7c999069c99e452d8d923bba8940990b8
  • Pointer size: 131 Bytes
  • Size of remote file: 111 kB
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ build-essential
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pillow
2
+ numpy