Spaces:
Sleeping
Sleeping
File size: 6,612 Bytes
22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 44402f8 22cc751 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | #!/usr/bin/env python3
"""
ํ ์ฅ ์ด์์ ์ด๋ฏธ์ง์ ๋ํด /analyze v1 ๊ณผ ๋์ผํ ํ์ดํ๋ผ์ธ์ ๋๋ฆฌ๊ณ
`<stem>_analyze_response.json`, `<stem>_analyze_summary.txt` ๋ฅผ ์๋๋ค.
์ฌ๋ฌ ์ฅ์ด๋ฉด ์
๋ก๋ ์์์ ๊ฐ์ด ํ ์์ฒญ์ผ๋ก ๋ณํฉํฉ๋๋ค.
ํ๋ก์ ํธ ๋ฃจํธ์์:
python dump_sample_analyze_artifacts.py sample_oneline_0.png
python dump_sample_analyze_artifacts.py a.png b.png c.png
python dump_sample_analyze_artifacts.py sample_imgs/sample_c.jpeg --return-debug
"""
from __future__ import annotations
import argparse
import json
import sys
import uuid
from pathlib import Path
from typing import Any, Dict, List
import cv2
ROOT = Path(__file__).resolve().parent
SAMPLE_IMGS = ROOT / "sample_imgs"
ALLOWED_EXT = {".jpg", ".jpeg", ".png", ".webp"}
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import main as stella_main # noqa: E402
def _resolve_image_path(name_or_path: str) -> Path:
raw = Path(name_or_path)
if raw.is_file():
return raw.resolve()
candidate = SAMPLE_IMGS / raw.name
if candidate.is_file():
return candidate.resolve()
raise FileNotFoundError(
f"์ด๋ฏธ์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค: {name_or_path!r} "
f"(๋ฃจํธ ์๋ ๊ฒฝ๋ก ๋๋ {SAMPLE_IMGS.name}/ ์์ ํ์ผ ์ด๋ฆ์ ์ฃผ์ธ์.)"
)
def _load_decoded(path: Path) -> Dict[str, Any]:
ext = path.suffix.lower()
if ext not in ALLOWED_EXT:
raise ValueError(f"์ง์ํ์ง ์๋ ํ์ฅ์์
๋๋ค: {ext} (ํ์ฉ: {sorted(ALLOWED_EXT)})")
image = cv2.imread(str(path), cv2.IMREAD_COLOR)
if image is None:
raise ValueError(f"์ด๋ฏธ์ง๋ฅผ ๋์ฝ๋ฉํ ์ ์์ต๋๋ค: {path}")
h, w = image.shape[:2]
return {
"filename": path.name,
"bytes": int(path.stat().st_size),
"width": int(w),
"height": int(h),
"image": image,
}
def _default_score_context() -> Dict[str, Any]:
return {
"clef": "treble",
"key_signature": {"fifths": -1},
"time_signature": "4/4",
"tempo_bpm_reference": None,
"divisions": 4,
}
def _build_analyze_response(
decoded: List[Dict[str, Any]],
score_context: Dict[str, Any],
*,
return_debug: bool,
) -> Dict[str, Any]:
body = stella_main.build_analyze_response_v1(
decoded,
score_context,
return_debug=return_debug,
)
body["request_id"] = str(uuid.uuid4())
return body
def _format_event_table(events: List[Dict[str, Any]]) -> str:
header = f"{'idx':>3} {'onset':>5} {'dur':>3} {'step':>4} {'oct':>3} {'alt':>3} type"
sep = "-" * 50
lines = [header, sep]
for i, ev in enumerate(events, start=1):
onset = ev.get("onset_div", "")
dur = ev.get("duration_div", "")
typ = ev.get("type", "")
if typ == "rest":
lines.append(f"{i:>3} {onset:>5} {dur:>3} {'':>4} {'':>3} {'':>3} {typ}")
else:
step = ev.get("step", "")
oct_ = ev.get("octave", "")
alt = ev.get("alter", "")
lines.append(f"{i:>3} {onset:>5} {dur:>3} {str(step):>4} {str(oct_):>3} {str(alt):>3} {typ}")
return "\n".join(lines)
def build_summary_text(response: Dict[str, Any]) -> str:
meta = response["meta"]
tl = response["timeline"]
sc = response["score_context"]
mel = response["melody"]
lines: List[str] = [
f"request_id: {response['request_id']}",
f"source: {json.dumps(response.get('source'), ensure_ascii=False)}",
f"warnings: {json.dumps(response['warnings'], ensure_ascii=False)}",
f"score_context: {json.dumps(sc, ensure_ascii=False)}",
f"segment_map: {json.dumps(response.get('segment_map'), ensure_ascii=False)}",
f"meta.preprocess: {json.dumps(meta.get('preprocess'), ensure_ascii=False)}",
f"pipeline_mode: {meta.get('pipeline_mode')}",
f"timeline: {json.dumps({'divisions': tl.get('divisions'), 'time_signature': tl.get('time_signature')}, ensure_ascii=False)}",
"",
f"--- melody ({mel.get('voice_id')}) reduction={mel.get('reduction_rule')} events={len(mel.get('events', []))} ---",
_format_event_table(mel.get("events", [])),
"",
]
while lines and lines[-1] == "":
lines.pop()
return "\n".join(lines) + "\n"
def _output_stem(paths: List[Path]) -> str:
if len(paths) == 1:
return paths[0].stem
return "__".join(p.stem for p in paths)
def main() -> None:
parser = argparse.ArgumentParser(
description="์ด๋ฏธ์ง 1์ฅ ์ด์์ ๋ํด analyze v1 ํ์ดํ๋ผ์ธ ๊ฒฐ๊ณผ๋ฅผ JSONยท์์ฝ ํ
์คํธ๋ก ์ ์ฅํฉ๋๋ค."
)
parser.add_argument(
"filenames",
nargs="+",
metavar="IMAGE",
help=(
f"์ด๋ฏธ์ง ๊ฒฝ๋ก 1๊ฐ ์ด์ (์์ = ์
๋ณด ์ด์ด์ง). "
f"ํ์ผ ์ด๋ฆ๋ง ์ฃผ๋ฉด {SAMPLE_IMGS.name}/ ์์ ์ฐพ์ต๋๋ค."
),
)
parser.add_argument(
"--out-dir",
type=Path,
default=ROOT / "artifacts",
help=f"์ถ๋ ฅ ๋๋ ํฐ๋ฆฌ (๊ธฐ๋ณธ: {ROOT.name}/artifacts)",
)
parser.add_argument(
"--score-context-json",
type=str,
default=None,
help="JSON ๋ฌธ์์ด (๊ธฐ๋ณธ: treble, fifths=-1, 4/4)",
)
parser.add_argument("--return-debug", action="store_true")
args = parser.parse_args()
paths = [_resolve_image_path(name) for name in args.filenames]
stem = _output_stem(paths)
out_dir = args.out_dir.resolve()
out_dir.mkdir(parents=True, exist_ok=True)
json_path = out_dir / f"{stem}_analyze_response.json"
txt_path = out_dir / f"{stem}_analyze_summary.txt"
if args.score_context_json:
score_ctx = json.loads(args.score_context_json)
if not isinstance(score_ctx, dict):
raise ValueError("score_context JSON must be an object")
else:
score_ctx = _default_score_context()
decoded = [_load_decoded(p) for p in paths]
response = _build_analyze_response(
decoded,
score_ctx,
return_debug=args.return_debug,
)
json_path.write_text(json.dumps(response, ensure_ascii=False, indent=2), encoding="utf-8")
txt_path.write_text(build_summary_text(response), encoding="utf-8")
print(f"Wrote {json_path}")
print(f"Wrote {txt_path}")
if __name__ == "__main__":
try:
main()
except (FileNotFoundError, ValueError, json.JSONDecodeError, stella_main.SingleStaffAnalyzeError) as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
|