wxnono commited on
Commit
7ee93c5
·
verified ·
1 Parent(s): a22d281

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from PIL import Image
4
+ from transformers import AutoProcessor, VisionEncoderDecoderModel
5
+
6
+ # 1. 自动从系统安全凭证中读取你的 Hugging Face Token
7
+ # (确保你已经按照上一步在 Space Settings 的 Secrets 里添加了 HF_TOKEN)
8
+ hf_token = os.environ.get("HF_TOKEN")
9
+
10
+ # 2. 定义 LEGATO 模型名称(如果作者更新了规模,可替换为其他大小的权重,如 legato-base)
11
+ MODEL_ID = "guangyangmusic/legato-small"
12
+
13
+ print("正在从 Hugging Face 缓存加载 LEGATO OMR 模型...")
14
+ # 使用 token 参数来确保有权下载该模型
15
+ processor = AutoProcessor.from_pretrained(MODEL_ID, token=hf_token)
16
+ model = VisionEncoderDecoderModel.from_pretrained(MODEL_ID, token=hf_token)
17
+ print("模型加载成功!")
18
+
19
+ def run_legato_omr(image):
20
+ if image is None:
21
+ return "请先上传一张清晰的乐谱截图!"
22
+
23
+ # 3. 图像预处理与模型推理
24
+ try:
25
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values
26
+
27
+ # 针对 CPU 环境,可以使用 generate 限制最大长度防止超时
28
+ generated_ids = model.generate(pixel_values, max_length=512)
29
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
30
+
31
+ return generated_text
32
+ except Exception as e:
33
+ return f"推理过程中出错: {str(e)}"
34
+
35
+ # 4. 搭建简洁的 Gradio 网页交互界面
36
+ demo = gr.Interface(
37
+ fn=run_legato_omr,
38
+ inputs=gr.Image(type="pil", label="1. 上传单行或单页乐谱图片"),
39
+ outputs=gr.Textbox(label="2. LEGATO 识别输出 (ABC 记谱法文本)", show_copy_button=True),
40
+ title="🎼 LEGATO 乐谱端到端识别系统",
41
+ description="基于大尺寸端到端通用 OMR 模型 LEGATO。上传乐谱图片,即可自动转化为可编辑的 ABC 记谱文本。"
42
+ )
43
+
44
+ if __name__ == "__main__":
45
+ demo.launch()