wxnono commited on
Commit
bdfff0c
·
verified ·
1 Parent(s): 838693f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -28
app.py CHANGED
@@ -1,54 +1,54 @@
1
  import os
 
2
  import gradio as gr
3
- import torch
4
  from PIL import Image
5
- from transformers import AutoProcessor, AutoModelForImageTextToText
6
 
7
  # 1. Safely extract your secure secret token
8
  hf_token = os.environ.get("HF_TOKEN")
9
 
10
- # 2. Define target repository path
11
  MODEL_ID = "guangyangmusic/legato-small"
 
12
 
13
- print("Loading model architecture and weights...")
14
-
15
- # FIX: Use the updated AutoModelForImageTextToText class for modern transformers compatibility
16
- processor = AutoProcessor.from_pretrained(MODEL_ID, token=hf_token, trust_remote_code=True)
17
- model = AutoModelForImageTextToText.from_pretrained(
18
- MODEL_ID,
19
- token=hf_token,
20
- trust_remote_code=True,
21
- torch_dtype=torch.bfloat16, # Lowers operational RAM allocation to under 16GB
22
- low_cpu_mem_usage=True # Prevents transient configuration-phase crashes
23
- )
24
-
25
- model.eval()
26
- print("🎉 LEGATO architecture successfully instantiated!")
27
 
28
  def run_legato_omr(image):
29
  if image is None:
30
  return "Please upload a sheet music image first!"
31
 
32
  try:
33
- # Pass visual assets into the tokenizer pipeline
34
- inputs = processor(images=image, return_tensors="pt")
 
 
35
 
36
- # CPU-isolated matrix multiplication
37
- with torch.no_grad():
38
- generated_ids = model.generate(**inputs, max_new_tokens=512)
39
- generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
40
 
41
- return generated_text if isinstance(generated_text, list) else generated_text
 
 
 
 
 
 
 
42
  except Exception as e:
43
- return f"Inference pipeline execution error: {str(e)}"
 
 
 
 
44
 
45
  # 3. Present UI layout blocks
46
  demo = gr.Interface(
47
  fn=run_legato_omr,
48
  inputs=gr.Image(type="pil", label="1. Upload Sheet Music Snippet"),
49
  outputs=gr.Textbox(label="2. LEGATO Output (ABC Notation Text)", show_copy_button=True),
50
- title="🎼 LEGATO End-to-End OMR Engine",
51
- description="Running entirely inside cloud-native CPU constraints. Music recognition cycles take 10-15 seconds."
52
  )
53
 
54
  if __name__ == "__main__":
@@ -56,4 +56,3 @@ if __name__ == "__main__":
56
 
57
 
58
 
59
-
 
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. Safely extract your secure secret token
8
  hf_token = os.environ.get("HF_TOKEN")
9
 
10
+ # 2. Initialize the optimized serverless client targeting LEGATO
11
  MODEL_ID = "guangyangmusic/legato-small"
12
+ client = InferenceClient(model=MODEL_ID, token=hf_token)
13
 
14
+ print("Hugging Face API Pipeline active. Forwarding inference tasks...")
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  def run_legato_omr(image):
17
  if image is None:
18
  return "Please upload a sheet music image first!"
19
 
20
  try:
21
+ # Convert PIL Image to raw bytes for standard network payload streaming
22
+ buffered = io.BytesIO()
23
+ image.save(buffered, format="JPEG")
24
+ image_bytes = buffered.getvalue()
25
 
26
+ # Stream the image asset straight to the dedicated model architecture host
27
+ print("Sending payload to Hugging Face Inference clusters...")
28
+ response = client.image_to_text(image_bytes)
 
29
 
30
+ # Handle different inference response formats
31
+ if hasattr(response, 'generated_text'):
32
+ return response.generated_text
33
+ elif isinstance(response, dict) and "generated_text" in response:
34
+ return response["generated_text"]
35
+ else:
36
+ return str(response)
37
+
38
  except Exception as e:
39
+ return (
40
+ f"API Inference Call Error: {str(e)}\n\n"
41
+ "💡 Tip: Ensure your HF_TOKEN has 'Read' access, and that "
42
+ "the model page doesn't require separate terms acceptance."
43
+ )
44
 
45
  # 3. Present UI layout blocks
46
  demo = gr.Interface(
47
  fn=run_legato_omr,
48
  inputs=gr.Image(type="pil", label="1. Upload Sheet Music Snippet"),
49
  outputs=gr.Textbox(label="2. LEGATO Output (ABC Notation Text)", show_copy_button=True),
50
+ title="🎼 LEGATO End-to-End OMR Engine (API Optimized)",
51
+ description="Proxied through Hugging Face's serverless pipeline to bypass local 16GB CPU limits. Transcriptions finish in seconds."
52
  )
53
 
54
  if __name__ == "__main__":
 
56
 
57
 
58