import argparse
import json
import sys
import time
import unicodedata

from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess


def clean_text(value: str) -> str:
    text = rich_transcription_postprocess(value or "")
    return "".join(char for char in text if unicodedata.category(char) != "So").strip()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--audio", required=True)
    parser.add_argument("--model-dir", required=True)
    parser.add_argument("--vad-model-dir", required=True)
    parser.add_argument("--device", default="cpu")
    args = parser.parse_args()

    model = AutoModel(
        model=args.model_dir,
        vad_model=args.vad_model_dir,
        device=args.device,
        disable_update=True,
    )
    started = time.perf_counter()
    result = model.generate(
        input=args.audio,
        language="zh",
        use_itn=True,
        batch_size_s=60,
    )
    text = result[0].get("text", "") if result else ""
    print(json.dumps({
        "ok": True,
        "text": clean_text(text),
        "latency_ms": round((time.perf_counter() - started) * 1000),
        "language": "zh",
        "engine": "sensevoice-small",
    }, ensure_ascii=False), flush=True)


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    main()
