Spaces:
Build error

ImageToScript / app.py
wxnono's picture
Update app.py
f3eedb7 verified
Raw History Blame
1.98 kB
import os
import gradio as gr
import torch
from PIL import Image
from transformers import AutoProcessor
# Import the custom model architecture directly from the installed legato package
from legato.models import LegatoModel
# 1. Safely pull your secret token
hf_token = os.environ.get("HF_TOKEN")
# 2. Define the exact model identifier
MODEL_ID = "guangyangmusic/legato-small"
print("Loading custom LEGATO OMR model architecture...")
# Initialize the processor and the specialized model class
processor = AutoProcessor.from_pretrained(MODEL_ID, token=hf_token)
model = LegatoModel.from_pretrained(
MODEL_ID,
token=hf_token,
torch_dtype=torch.bfloat16, # Drastically cuts RAM usage to fit 16GB CPU limits
low_cpu_mem_usage=True # Prevents system memory spikes during loading
)
model.eval()
print("LEGATO Model loaded successfully!")
def run_legato_omr(image):
if image is None:
return "Please upload a sheet music image first!"
try:
# Preprocess the incoming image snippet
inputs = processor(images=image, return_tensors="pt")
# Execute token inference securely
with torch.no_grad():
generated_ids = model.generate(**inputs, max_new_tokens=512)
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
return generated_text[0] if isinstance(generated_text, list) else generated_text
except Exception as e:
return f"Inference Pipeline Error: {str(e)}"
# 3. Gradio Interface Declaration
demo = gr.Interface(
fn=run_legato_omr,
inputs=gr.Image(type="pil", label="1. Upload Sheet Music Snippet"),
outputs=gr.Textbox(label="2. LEGATO Output (ABC Notation Text)", show_copy_button=True),
title="🎼 LEGATO End-to-End OMR Engine",
description="Running on optimized CPU spaces. Generates machine-readable musical markup from raw notation images."
)
if __name__ == "__main__":
demo.launch()