wxnono commited on
Commit
96ceabc
·
verified ·
1 Parent(s): 63f5f29

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -45
app.py CHANGED
@@ -1,67 +1,126 @@
1
  import os
2
- import io
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
- from PIL import Image
5
- from huggingface_hub import InferenceClient
 
 
6
 
7
- # 1. Access secure system keys
8
- hf_token = os.environ.get("HF_TOKEN")
 
 
 
9
  MODEL_ID = "guangyangmusic/legato-small"
 
 
 
 
 
10
 
11
- print("Hugging Face API Pipeline active. Forwarding inference tasks...")
 
 
 
 
12
 
13
- # 2. Build the explicit serverless inference router
14
- def run_legato_omr(image):
 
 
 
 
15
  if image is None:
16
  return "Please upload a sheet music image first!"
17
-
18
  try:
19
- # Convert incoming canvas/image assets to generic bytes array
20
- buffered = io.BytesIO()
21
- image.save(buffered, format="JPEG")
22
- image_bytes = buffered.getvalue()
23
-
24
- # Instantiate localized pipeline execution clients
25
- client = InferenceClient(model=MODEL_ID, token=hf_token, timeout=30)
26
-
27
- print("Streaming asset matrices to Hugging Face cluster...")
28
- response = client.post(data=image_bytes, model=MODEL_ID)
29
- result_text = response.decode("utf-8")
30
-
31
- if not result_text or "error" in result_text.lower():
32
- return f"Cluster Warmup Alert: The remote model is currently spinning up its parameters. Please resubmit this image in 10-15 seconds.\n\nDetails: {result_text}"
33
-
34
- return result_text
35
-
36
- except Exception as e:
 
 
37
  return (
38
- f"API Communication Exception: {str(e)}\n\n"
39
- "💡 Troubleshooting Tips:\n"
40
- "1. If a 'Timeout' occurred, the remote server is spinning up. Try again in a minute.\n"
41
- "2. Ensure your Space Secret Key is exactly named HF_TOKEN and contains a valid 'Read' token."
42
  )
 
 
43
 
44
- # 3. Formulate the visual block interface
 
 
 
45
  with gr.Blocks() as demo:
46
- gr.Markdown("# 🎼 LEGATO End-to-End OMR Engine (API Cluster Layer)")
47
- gr.Markdown("Proxied via serverless API hooks to bypass local 16GB CPU limits. Conversions take 2-5 seconds per line snippet.")
48
-
 
 
 
 
49
  with gr.Row():
50
  with gr.Column():
51
  input_image = gr.Image(type="pil", label="1. Upload Sheet Music Snippet")
52
  submit_btn = gr.Button("Analyze Layout & Transcribe", variant="primary")
53
- with gr.Column():
54
- output_text = gr.Textbox(label="2. LEGATO Output (ABC Notation)", lines=12)
55
-
56
- submit_btn.click(fn=run_legato_omr, inputs=input_image, outputs=output_text)
57
 
58
- # 4. FIXED: Removed 'ssr' parameter to prevent version mismatch crash
59
- if __name__ == "__main__":
60
- demo.queue().launch(
61
- server_name="0.0.0.0",
62
- server_port=7860,
63
- )
 
 
 
 
 
64
 
 
 
 
 
65
 
 
 
 
 
 
66
 
 
 
67
 
 
1
  import os
2
+ import subprocess
3
+ import sys
4
+
5
+ # `spaces` must be imported before torch so ZeroGPU can patch CUDA init.
6
+ import spaces
7
+
8
+ # ---------------------------------------------------------------------------
9
+ # 1. Bootstrap the legato codebase.
10
+ # The repo ships no setup.py/pyproject.toml, so it cannot be pip-installed.
11
+ # Clone it and put the package directory on sys.path instead.
12
+ # ---------------------------------------------------------------------------
13
+ LEGATO_DIR = "/home/user/app/legato_src"
14
+ LEGATO_REPO = "https://github.com/guang-yng/legato.git"
15
+
16
+ if not os.path.isdir(LEGATO_DIR):
17
+ print("Cloning legato codebase...")
18
+ subprocess.run(["git", "clone", "--depth", "1", LEGATO_REPO, LEGATO_DIR], check=True)
19
+
20
+ if LEGATO_DIR not in sys.path:
21
+ sys.path.insert(0, LEGATO_DIR)
22
+
23
  import gradio as gr
24
+ import torch
25
+ from transformers import AutoProcessor, GenerationConfig
26
+
27
+ from legato.models import LegatoModel
28
 
29
+ # ---------------------------------------------------------------------------
30
+ # 2. Load the model once at startup.
31
+ # The vision encoder pulls from the gated meta-llama/Llama-3.2-11B-Vision,
32
+ # so HF_TOKEN must belong to an account that accepted the Llama 3.2 license.
33
+ # ---------------------------------------------------------------------------
34
  MODEL_ID = "guangyangmusic/legato-small"
35
+ HF_TOKEN = os.environ.get("HF_TOKEN")
36
+
37
+ print(f"Loading {MODEL_ID}...")
38
+ model = LegatoModel.from_pretrained(MODEL_ID, token=HF_TOKEN)
39
+ processor = AutoProcessor.from_pretrained(MODEL_ID, token=HF_TOKEN)
40
 
41
+ # fp16 halves the ~15GB full-precision footprint. Under ZeroGPU the .to("cuda")
42
+ # is deferred until the first @spaces.GPU call, which is the supported pattern.
43
+ model = model.half().to("cuda")
44
+ model.eval()
45
+ print("Model loaded.")
46
 
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # 3. Inference. The @spaces.GPU decorator is what ZeroGPU scans for at startup.
50
+ # ---------------------------------------------------------------------------
51
+ @spaces.GPU(duration=120)
52
+ def run_legato_omr(image, num_beams, max_length):
53
  if image is None:
54
  return "Please upload a sheet music image first!"
55
+
56
  try:
57
+ # convert() guards against RGBA/grayscale/palette PNGs, which are common
58
+ # for score screenshots and would otherwise fail downstream.
59
+ image = image.convert("RGB")
60
+
61
+ inputs = processor(images=image, return_tensors="pt")
62
+ inputs = {k: v.to("cuda") for k, v in inputs.items()}
63
+
64
+ generation_config = GenerationConfig(
65
+ max_length=int(max_length),
66
+ num_beams=int(num_beams),
67
+ repetition_penalty=1.1,
68
+ )
69
+
70
+ with torch.no_grad():
71
+ outputs = model.generate(**inputs, generation_config=generation_config)
72
+
73
+ return processor.batch_decode(outputs, skip_special_tokens=True)[0]
74
+
75
+ except torch.cuda.OutOfMemoryError:
76
+ torch.cuda.empty_cache()
77
  return (
78
+ "Out of GPU memory. Try a smaller image crop, or lower the beam count "
79
+ "in Advanced settings."
 
 
80
  )
81
+ except Exception as e:
82
+ return f"Inference failed: {type(e).__name__}: {e}"
83
 
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # 4. Interface
87
+ # ---------------------------------------------------------------------------
88
  with gr.Blocks() as demo:
89
+ gr.Markdown("# 🎼 LEGATO End-to-End OMR")
90
+ gr.Markdown(
91
+ "Transcribes typeset sheet music into ABC notation. "
92
+ "Works best on a single clean staff line or a short snippet; "
93
+ "handwritten and low-quality scans are out of scope for this model."
94
+ )
95
+
96
  with gr.Row():
97
  with gr.Column():
98
  input_image = gr.Image(type="pil", label="1. Upload Sheet Music Snippet")
99
  submit_btn = gr.Button("Analyze Layout & Transcribe", variant="primary")
 
 
 
 
100
 
101
+ with gr.Accordion("Advanced settings", open=False):
102
+ num_beams = gr.Slider(
103
+ 1, 10, value=4, step=1,
104
+ label="Beam count",
105
+ info="The model card uses 10. Higher is more accurate but "
106
+ "much slower — 10 can exceed the ZeroGPU time limit.",
107
+ )
108
+ max_length = gr.Slider(
109
+ 256, 2048, value=2048, step=256,
110
+ label="Max tokens",
111
+ )
112
 
113
+ with gr.Column():
114
+ output_text = gr.Textbox(
115
+ label="2. LEGATO Output (ABC Notation)", lines=12, show_copy_button=True
116
+ )
117
 
118
+ submit_btn.click(
119
+ fn=run_legato_omr,
120
+ inputs=[input_image, num_beams, max_length],
121
+ outputs=output_text,
122
+ )
123
 
124
+ if __name__ == "__main__":
125
+ demo.queue().launch(server_name="0.0.0.0", server_port=7860)
126