Ksu2023 commited on
Commit
1f06f62
·
verified ·
1 Parent(s): 34c1b12

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +51 -9
  2. app.py +14 -0
  3. omr_backend.py +219 -0
  4. requirements.txt +6 -0
README.md CHANGED
@@ -1,14 +1,56 @@
1
  ---
2
- title: Test
3
- emoji: 🔥
4
- colorFrom: blue
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 6.27.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
11
- short_description: tsets
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: OMR Comparator Backend
3
+ emoji: 🎼
4
+ colorFrom: yellow
5
+ colorTo: gray
6
  sdk: gradio
 
 
7
  app_file: app.py
8
+ suggested_hardware: cpu-basic
 
9
  ---
10
 
11
+ # OMR Comparator Backend
12
+
13
+ This is the public FastAPI gateway used by the OMR Bench v0 app. The Space uses the free Gradio SDK runner and starts the FastAPI gateway from `app.py`; no paid Docker hardware is required.
14
+
15
+ ## Important
16
+
17
+ The gateway does not contain the six model runtimes. It proxies requests to model services configured with environment variables:
18
+
19
+ - `ROKOT_REMOTE_URL`
20
+ - `LEGATO_REMOTE_URL`
21
+ - `TRANSCODA_REMOTE_URL`
22
+ - `SMT_REMOTE_URL`
23
+ - `HOMR_REMOTE_URL`
24
+ - `FLOVA_REMOTE_URL`
25
+
26
+ Each remote service must accept a multipart upload at the configured URL and return either MusicXML text or JSON containing `musicxml`, `xml`, `music_xml`, or `result`.
27
+
28
+ Optional upload field overrides:
29
+
30
+ - `ROKOT_REMOTE_FIELD`
31
+ - `LEGATO_REMOTE_FIELD`
32
+ - `TRANSCODA_REMOTE_FIELD`
33
+ - `SMT_REMOTE_FIELD`
34
+ - `HOMR_REMOTE_FIELD`
35
+ - `FLOVA_REMOTE_FIELD`
36
+
37
+ They default to `image`.
38
+
39
+ ## Health check
40
+
41
+ Open `/` after deployment. It reports the six model IDs and how many remote adapters are configured.
42
+
43
+ ## Local run
44
+
45
+ ```bash
46
+ pip install -r requirements.txt
47
+ uvicorn omr_backend:app --host 0.0.0.0 --port 8000
48
+ ```
49
+
50
+ ## v0 Preview
51
+
52
+ Use the public HTTPS Space URL in OMR Bench Settings, for example:
53
+
54
+ `https://YOUR-SPACE-NAME.hf.space`
55
+
56
+ Do not use `localhost` or `127.0.0.1` in v0 Preview.
app.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uvicorn
3
+ import spaces
4
+ from omr_backend import app
5
+
6
+
7
+ @spaces.GPU
8
+ async def zero_gpu_ready():
9
+ """Registers this Space as ZeroGPU-compatible."""
10
+ return {"ok": True}
11
+
12
+
13
+ if __name__ == "__main__":
14
+ uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))
omr_backend.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unified backend contract for omr_comparator.html
3
+
4
+ This file intentionally separates the browser UI from heavyweight model inference.
5
+ Run each model locally / on a GPU server / in a Hugging Face Space, then normalize its
6
+ result to the same JSON shape.
7
+
8
+ The frontend calls:
9
+ POST /api/omr/{model_id}
10
+ multipart field:
11
+ image = PNG
12
+
13
+ Expected response:
14
+ {
15
+ "musicxml": "<score-partwise ...>",
16
+ "raw_output": "... optional ABC/**kern/beKern/LilyPond ...",
17
+ "raw_format": "abc|kern|bekern|lilypond|musicxml",
18
+ "elapsed_ms": 1234,
19
+ "warnings": []
20
+ }
21
+
22
+ This template includes:
23
+ - FastAPI routing + CORS
24
+ - image upload handling
25
+ - an HTTP proxy adapter for separately hosted model endpoints
26
+ - a CLI adapter pattern for local tools such as homr
27
+
28
+ It deliberately does NOT pretend all six models share one Python runtime: LEGATO,
29
+ Rokot/Qwen3-VL, homr and SMT have conflicting/heavy dependencies and are much easier
30
+ to keep in separate containers.
31
+ """
32
+
33
+ from __future__ import annotations
34
+ import base64, json, os, subprocess, tempfile, time
35
+ from pathlib import Path
36
+ from typing import Optional
37
+
38
+ import httpx
39
+ from fastapi import FastAPI, File, HTTPException, UploadFile
40
+ from fastapi.middleware.cors import CORSMiddleware
41
+
42
+ app = FastAPI(title="OMR Comparator Backend")
43
+ app.add_middleware(
44
+ CORSMiddleware,
45
+ allow_origins=["*"], allow_credentials=False,
46
+ allow_methods=["*"], allow_headers=["*"],
47
+ )
48
+
49
+ MODEL_IDS = {"rokot", "legato", "transcoda", "smt", "homr", "flova"}
50
+
51
+ # Optional: point each adapter at an independently deployed service.
52
+ # Example:
53
+ # export LEGATO_REMOTE_URL=https://my-legato-space.hf.space/omr
54
+ REMOTE = {
55
+ m: os.getenv(f"{m.upper()}_REMOTE_URL", "").strip()
56
+ for m in MODEL_IDS
57
+ }
58
+ REMOTE_FIELD = {
59
+ m: os.getenv(f"{m.upper()}_REMOTE_FIELD", "image").strip() or "image"
60
+ for m in MODEL_IDS
61
+ }
62
+
63
+
64
+ @app.get("/")
65
+ def health():
66
+ return {
67
+ "ok": True,
68
+ "models": sorted(MODEL_IDS),
69
+ "remote": {k: bool(v) for k, v in REMOTE.items()},
70
+ "remote_fields": REMOTE_FIELD,
71
+ "configured_count": sum(bool(v) for v in REMOTE.values()),
72
+ }
73
+
74
+
75
+ @app.post("/api/omr/{model_id}")
76
+ async def run_omr(model_id: str, image: UploadFile = File(...)):
77
+ if model_id not in MODEL_IDS:
78
+ raise HTTPException(404, f"Unknown model: {model_id}")
79
+
80
+ data = await image.read()
81
+ if not data:
82
+ raise HTTPException(400, "Empty image")
83
+
84
+ started = time.perf_counter()
85
+
86
+ # Recommended production setup: one container / Space per model.
87
+ if REMOTE.get(model_id):
88
+ result = await proxy_model(model_id, data, image.filename or "page.png")
89
+ result.setdefault("elapsed_ms", int((time.perf_counter()-started)*1000))
90
+ return result
91
+
92
+ # homr is the easiest model to wire locally because it already exports MusicXML.
93
+ if model_id == "homr" and os.getenv("HOMR_LOCAL", "0") == "1":
94
+ result = run_homr_cli(data)
95
+ result.setdefault("elapsed_ms", int((time.perf_counter()-started)*1000))
96
+ return result
97
+
98
+ raise HTTPException(
99
+ 503,
100
+ detail=(
101
+ f"{model_id} adapter is not configured. Set "
102
+ f"{model_id.upper()}_REMOTE_URL to a model service returning MusicXML, "
103
+ f"or add a local adapter in omr_backend.py."
104
+ ),
105
+ )
106
+
107
+
108
+ async def proxy_model(model_id: str, image_bytes: bytes, filename: str):
109
+ url = REMOTE[model_id]
110
+ async with httpx.AsyncClient(timeout=600) as client:
111
+ field = REMOTE_FIELD[model_id]
112
+ r = await client.post(
113
+ url,
114
+ files={field: (filename, image_bytes, "image/png")},
115
+ )
116
+ if r.status_code >= 400:
117
+ raise HTTPException(r.status_code, f"{model_id} remote error: {r.text[:1500]}")
118
+
119
+ ctype = r.headers.get("content-type", "")
120
+ if "application/json" in ctype:
121
+ payload = r.json()
122
+ return normalize_payload(payload)
123
+
124
+ # A model service is also allowed to return raw MusicXML.
125
+ text = r.text
126
+ if text.lstrip().startswith("<"):
127
+ return {"musicxml": text, "raw_output": text, "raw_format": "musicxml"}
128
+
129
+ raise HTTPException(502, f"{model_id} remote returned an unsupported response.")
130
+
131
+
132
+ def normalize_payload(p: dict):
133
+ """Accept common field names from model services and normalize them."""
134
+ if "musicxml" in p:
135
+ return p
136
+ for key in ("xml", "music_xml", "result"):
137
+ val = p.get(key)
138
+ if isinstance(val, str) and val.lstrip().startswith("<"):
139
+ p["musicxml"] = val
140
+ return p
141
+ return p
142
+
143
+
144
+ def run_homr_cli(image_bytes: bytes):
145
+ """
146
+ Local homr example.
147
+
148
+ Install homr separately and make the `homr` executable available in PATH.
149
+ Current homr supports camera images/PDF and writes MusicXML beside the input.
150
+ """
151
+ with tempfile.TemporaryDirectory(prefix="homr-") as td:
152
+ td = Path(td)
153
+ inp = td / "input.png"
154
+ inp.write_bytes(image_bytes)
155
+
156
+ proc = subprocess.run(
157
+ ["homr", str(inp)],
158
+ cwd=td,
159
+ stdout=subprocess.PIPE,
160
+ stderr=subprocess.STDOUT,
161
+ text=True,
162
+ timeout=600,
163
+ )
164
+ if proc.returncode != 0:
165
+ raise HTTPException(500, f"homr failed:\n{proc.stdout[-4000:]}")
166
+
167
+ candidates = list(td.glob("*.musicxml")) + list(td.glob("*.xml"))
168
+ if not candidates:
169
+ raise HTTPException(500, f"homr produced no MusicXML.\n{proc.stdout[-4000:]}")
170
+
171
+ xml = candidates[0].read_text("utf-8", errors="replace")
172
+ return {
173
+ "musicxml": xml,
174
+ "raw_output": proc.stdout,
175
+ "raw_format": "musicxml",
176
+ "warnings": [],
177
+ }
178
+
179
+
180
+ # ---------------------------------------------------------------------------
181
+ # MODEL-SPECIFIC SERVICE CONTRACTS
182
+ # ---------------------------------------------------------------------------
183
+ #
184
+ # Recommended: create one tiny service for each heavy model and set its URL via
185
+ # environment variable. Each service only needs one endpoint:
186
+ #
187
+ # POST /omr
188
+ # image: UploadFile
189
+ # -> {"musicxml": "...", "raw_output": "...", "raw_format": "..."}
190
+ #
191
+ # Conversion suggestions:
192
+ #
193
+ # Rokot:
194
+ # image (one music system) -> rokot-ABC.
195
+ # Convert ABC -> MusicXML with the project's preferred ABC converter.
196
+ #
197
+ # LEGATO:
198
+ # image -> ABC using the official legato codebase.
199
+ # The official repo/demo already includes ABC -> MusicXML conversion utilities.
200
+ #
201
+ # Transcoda:
202
+ # full page -> canonical **kern.
203
+ # Convert **kern -> MusicXML using a Humdrum/MusicXML converter.
204
+ #
205
+ # SMT / SMT++:
206
+ # piano page/system -> beKern.
207
+ # Reconstruct **kern, then convert **kern -> MusicXML.
208
+ #
209
+ # Flova:
210
+ # image -> LilyPond.
211
+ # Convert LilyPond -> MusicXML in a dedicated service (typically via an external
212
+ # notation converter; keep this outside the browser).
213
+ #
214
+ # Keeping these adapters isolated avoids dependency conflicts and lets each model
215
+ # use the GPU/runtime it expects.
216
+ #
217
+ # Start this gateway:
218
+ # pip install fastapi uvicorn python-multipart httpx
219
+ # uvicorn omr_backend:app --host 0.0.0.0 --port 8000
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ httpx
3
+ python-multipart
4
+ uvicorn[standard]
5
+ gradio
6
+ spaces