wxnono commited on
Commit
1905139
·
verified ·
1 Parent(s): ccf2f61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -46
app.py CHANGED
@@ -1,81 +1,54 @@
1
  import os
2
- import sys
3
- import zipfile
4
- import urllib.request
5
-
6
- # 1. Manually stream and extract the source package to bypass pip routing limits
7
- REPO_ZIP_URL = "https://github.com"
8
- ZIP_FILE = "legato-main.zip"
9
- EXTRACT_DIR = "legato_source"
10
-
11
- if not os.path.exists(EXTRACT_DIR):
12
- print("Streaming LEGATO codebase via direct source zip channel...")
13
- try:
14
- # Download archive file cleanly over standard HTTP
15
- urllib.request.urlretrieve(REPO_ZIP_URL, ZIP_FILE)
16
-
17
- # Unpack the repository natively into workspace
18
- with zipfile.ZipFile(ZIP_FILE, 'r') as zip_ref:
19
- zip_ref.extractall(EXTRACT_DIR)
20
-
21
- print("Codebase successfully unzipped.")
22
- except Exception as e:
23
- print(f"Network streaming error: {str(e)}")
24
-
25
- # Mount the unzipped source directory to Python system paths
26
- MODULE_PATH = os.path.abspath(os.path.join(EXTRACT_DIR, "legato-main"))
27
- if MODULE_PATH not in sys.path:
28
- sys.path.insert(0, MODULE_PATH)
29
-
30
  import gradio as gr
31
  import torch
32
  from PIL import Image
33
- from transformers import AutoProcessor
34
-
35
- # Safe-check local module imports
36
- try:
37
- from legato.models import LegatoModel
38
- print("LEGATO layout modules successfully mapped.")
39
- except ImportError as err:
40
- raise ImportError(f"Directory structural validation failure: {str(err)}")
41
 
42
- # 2. Extract access tokens for Meta Llama framework checkpoints
43
  hf_token = os.environ.get("HF_TOKEN")
 
 
44
  MODEL_ID = "guangyangmusic/legato-small"
45
 
46
- print("Loading model matrices under bfloat16 memory target...")
47
- processor = AutoProcessor.from_pretrained(MODEL_ID, token=hf_token)
48
- model = LegatoModel.from_pretrained(
 
 
49
  MODEL_ID,
50
  token=hf_token,
51
- torch_dtype=torch.bfloat16, # Drops RAM overhead to fit inside 16GB limit
52
- low_cpu_mem_usage=True # Prevents peak memory crashes during initialization
 
53
  )
 
54
  model.eval()
55
- print("🎉 Model fully active in runtime memory.")
56
 
57
  def run_legato_omr(image):
58
  if image is None:
59
  return "Please upload a sheet music image first!"
60
 
61
  try:
 
62
  inputs = processor(images=image, return_tensors="pt")
63
 
 
64
  with torch.no_grad():
65
  generated_ids = model.generate(**inputs, max_new_tokens=512)
66
  generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
67
 
68
  return generated_text if isinstance(generated_text, list) else generated_text
69
  except Exception as e:
70
- return f"Inference Execution Timeout/Fault: {str(e)}"
71
 
72
- # 3. Gradio Interface Declaration
73
  demo = gr.Interface(
74
  fn=run_legato_omr,
75
  inputs=gr.Image(type="pil", label="1. Upload Sheet Music Snippet"),
76
  outputs=gr.Textbox(label="2. LEGATO Output (ABC Notation Text)", show_copy_button=True),
77
  title="🎼 LEGATO End-to-End OMR Engine",
78
- description="Running under CPU constraints. Processing music snapshots will take 10-15 seconds."
79
  )
80
 
81
  if __name__ == "__main__":
@@ -83,3 +56,4 @@ if __name__ == "__main__":
83
 
84
 
85
 
 
 
1
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
  import torch
4
  from PIL import Image
5
+ from transformers import AutoProcessor, AutoModelForVision2Seq
 
 
 
 
 
 
 
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 native model architecture and weights...")
14
+
15
+ # Pull the processor and custom model definition dynamically from the hub files
16
+ processor = AutoProcessor.from_pretrained(MODEL_ID, token=hf_token, trust_remote_code=True)
17
+ model = AutoModelForVision2Seq.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
 
57
 
58
 
59
+