Instructions to use MoYoYoTech/Translator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use MoYoYoTech/Translator with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf MoYoYoTech/Translator:Q5_0 # Run inference directly in the terminal: llama cli -hf MoYoYoTech/Translator:Q5_0
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf MoYoYoTech/Translator:Q5_0 # Run inference directly in the terminal: llama cli -hf MoYoYoTech/Translator:Q5_0
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf MoYoYoTech/Translator:Q5_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf MoYoYoTech/Translator:Q5_0
Use Docker
docker model run hf.co/MoYoYoTech/Translator:Q5_0
- Llama new
- LM Studio
- Jan
- Ollama
How to use MoYoYoTech/Translator with Ollama:
ollama run hf.co/MoYoYoTech/Translator:Q5_0
- Unsloth Desktop
- Pi
How to use MoYoYoTech/Translator with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf MoYoYoTech/Translator:Q5_0
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "MoYoYoTech/Translator:Q5_0" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use MoYoYoTech/Translator with Docker Model Runner:
docker model run hf.co/MoYoYoTech/Translator:Q5_0
- Lemonade
How to use MoYoYoTech/Translator with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull MoYoYoTech/Translator:Q5_0
Run and chat with the model
lemonade run user.Translator-Q5_0
List all available models
lemonade list
- Hermes Agent
How to use MoYoYoTech/Translator with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf MoYoYoTech/Translator:Q5_0
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default MoYoYoTech/Translator:Q5_0
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use MoYoYoTech/Translator with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf MoYoYoTech/Translator:Q5_0
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "MoYoYoTech/Translator:Q5_0" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
daihui.zhang commited on
Commit ·
6f13b8c
1
Parent(s): 485d8e3
change to pipelines multiple processing
Browse filesFiles changed (9)
12 unmodified lines13141516171812 unmodified linesBASE_DIR = pathlib.Path(__file__).parentMODEL_DIR = BASE_DIR / "moyoyo_asr_models"# 标点SENTENCE_END_MARKERS = ['.', '!', '?', '。', '!', '?', ';', ';', ':', ':']PAUSE_END_MARKERS = [',', ',', '、']12 unmodified lines1314151617181912 unmodified linesBASE_DIR = pathlib.Path(__file__).parentMODEL_DIR = BASE_DIR / "moyoyo_asr_models"ASSERT_DIR = BASE_DIR / "assets"# 标点SENTENCE_END_MARKERS = ['.', '!', '?', '。', '!', '?', ';', ';', ':', ':']PAUSE_END_MARKERS = [',', ',', '、']
12345612 unmodified lines1920212223242526272813 unmodified lines424344454647484950from dataclasses import dataclass, fieldfrom multiprocessing import Process@dataclassclass Segment:12 unmodified linesclass BasePipe(Process):def __init__(self, in_queue, out_queue) -> None:super().__init__() # Initialize the Process classself._in_queue = in_queueself._out_queue = out_queue@propertydef output_queue(self):13 unmodified linesdef run(self):self.init()while True:item = self._in_queue.get()if item is None: # Check for termination signalbreakout_item = self.process(item)self._out_queue.put(out_item)123456712 unmodified lines202122232425262728293031323334353637383913 unmodified lines53545556575859606162from dataclasses import dataclass, fieldfrom multiprocessing import Process, Queuefrom multiprocessing import Event@dataclassclass Segment:12 unmodified linesclass BasePipe(Process):def __init__(self, in_queue=None, out_queue=None) -> None:super().__init__() # Initialize the Process classself._in_queue = in_queue if in_queue else Queue()self._out_queue = out_queue if out_queue else Queue()self._ready = Event()def set_ready(self):self._ready.set()def is_ready(self):return self._ready.is_set()def wait(self):self._ready.wait()@propertydef output_queue(self):13 unmodified linesdef run(self):self.init()self.set_ready()while True:item = self.input_queue.get()if item is None: # Check for termination signalbreakout_item = self.process(item)self.output_queue.put(out_item)
3 unmodified lines4567893 unmodified linesfrom ..translator import QwenTranslatorfrom config import LLM_MODEL_PATH, LLM_SYS_PROMPTclass TranslatePipe(BasePipe):translator = None3 unmodified lines456789103 unmodified linesfrom ..translator import QwenTranslatorfrom config import LLM_MODEL_PATH, LLM_SYS_PROMPTclass TranslatePipe(BasePipe):translator = None
6 unmodified lines789101112136 unmodified linesclass WhisperPipe(BasePipe):whisper = Nonedef __init__(self, in_queue, out_queue) -> None:super().__init__(in_queue, out_queue)6 unmodified lines789101112136 unmodified linesclass WhisperPipe(BasePipe):whisper = Nonedef __init__(self, in_queue=None, out_queue=None) -> None:super().__init__(in_queue, out_queue)
175 unmodified lines176177178179180181182183175 unmodified linesframe_data = websocket.recv()if frame_data == b"END_OF_AUDIO":return Falsereturn np.frombuffer(frame_data, dtype=np.int16).astype(np.float32) / 32768.0# return np.frombuffer(frame_data, dtype=np.float32)def handle_new_connection(self, websocket):175 unmodified lines176177178179180181182183175 unmodified linesframe_data = websocket.recv()if frame_data == b"END_OF_AUDIO":return False# return np.frombuffer(frame_data, dtype=np.int16).astype(np.float32) / 32768.0return np.frombuffer(frame_data, dtype=np.float32)def handle_new_connection(self, websocket):
4 unmodified lines56789101112131415161718192021222324251 unmodified line2728293031323334353637384 unmodified linesclass TranslatePipes:def __init__(self) -> None:self.whisper_input_q = mp.Queue()self.translate_input_q = mp.Queue()self.result_queue = mp.Queue()# whisper 转录self._whisper_pipe = WhisperPipe(in_queue=self.whisper_input_q,out_queue=self.translate_input_q)# llm 翻译self._translate_pipe = TranslatePipe(in_queue=self.translate_input_q,out_queue=self.result_queue,)self._whisper_pipe.daemon = Trueself._whisper_pipe.start()1 unmodified lineself._translate_pipe.daemon = Trueself._translate_pipe.start()def translate(self, text, src_lang, dst_lang) -> MetaItem:item = MetaItem(transcribe_content=text,source_language=src_lang,destination_language=dst_lang)self._translate_pipe.input_queue.put(item)return self._translate_pipe.output_queue.get()4 unmodified lines5678910111213141516171819201 unmodified line2223242526272829303132333435364 unmodified linesclass TranslatePipes:def __init__(self) -> None:# self.whisper_input_q = mp.Queue()# self.translate_input_q = mp.Queue()# self.result_queue = mp.Queue()# whisper 转录self._whisper_pipe = WhisperPipe()# llm 翻译self._translate_pipe = TranslatePipe()self._whisper_pipe.daemon = Trueself._whisper_pipe.start()1 unmodified lineself._translate_pipe.daemon = Trueself._translate_pipe.start()def wait_ready(self):self._whisper_pipe.wait()self._translate_pipe.wait()def translate(self, text, src_lang, dst_lang) -> MetaItem:item = MetaItem(transcribe_content=text,source_language=src_lang,destination_language=dst_lang)self._translate_pipe.input_queue.put(item)return self._translate_pipe.output_queue.get()
7 unmodified lines89101112131415161718196 unmodified lines2627282930313233347 unmodified linesdef __init__(self, model_path, system_prompt="") -> None:self.llm = Llama(model_path=model_path,# n_gpu_layers=-1, # Uncomment to use GPU acceleration# seed=1337, # Uncomment to set a specific seed# n_ctx=2048, # Uncomment to increase the context windowchat_format="chatml",verbose=False)self.sys_prompt = system_promptdef to_message(self, prompt, src_lang, dst_lang):6 unmodified linesdef translate(self, prompt, src_lang, dst_lang) -> str:message = self.to_message(prompt, src_lang, dst_lang)start_time = time.monotonic()output = self.llm.create_chat_completion(messages=message, temperature=0.9)return output['choices'][0]['message']['content']def __call__(self, prompt,*args, **kwargs):7 unmodified lines891011121314156 unmodified lines222324252627287 unmodified linesdef __init__(self, model_path, system_prompt="") -> None:self.llm = Llama(model_path=model_path,chat_format="chatml",verbose=False)self.sys_prompt = system_promptdef to_message(self, prompt, src_lang, dst_lang):6 unmodified linesdef translate(self, prompt, src_lang, dst_lang) -> str:message = self.to_message(prompt, src_lang, dst_lang)output = self.llm.create_chat_completion(messages=message, temperature=0)return output['choices'][0]['message']['content']def __call__(self, prompt,*args, **kwargs):
19 unmodified lines202122232425268 unmodified lines353637383940414219 unmodified linesdef warmup(cls, warmup_steps=1):mel, _, = soundfile.read("assets/jfk.flac")for _ in range(warmup_steps):cls.model.transcribe(mel, print_progress=False)8 unmodified linesdef transcribe(self, audio_buffer:bytes, language):max_len, prompt = self.config_language(language)audio_buffer = np.frombuffer(audio_buffer, dtype=np.float32)print("audio buffer got:", len(audio_buffer))output = self.model.transcribe(audio_buffer,initial_prompt=prompt,language=language,19 unmodified lines202122232425268 unmodified lines3536373839404119 unmodified linesdef warmup(cls, warmup_steps=1):mel, _, = soundfile.read(f"{config.ASSERT_DIR}/jfk.flac")for _ in range(warmup_steps):cls.model.transcribe(mel, print_progress=False)8 unmodified linesdef transcribe(self, audio_buffer:bytes, language):max_len, prompt = self.config_language(language)audio_buffer = np.frombuffer(audio_buffer, dtype=np.float32)output = self.model.transcribe(audio_buffer,initial_prompt=prompt,language=language,
19 unmodified lines2021222324252627281 unmodified line30313233343536373817 unmodified lines5657585960616249 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811826 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152162172184 unmodified lines22322422522622722822923023123223323423523623723823924024124218 unmodified lines2612622632642652662672682692704 unmodified lines27527627727827928028128228328428528640 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483492 unmodified lines35235335435535635735835963 unmodified lines42342442542642742842919 unmodified linesfrom scipy.io.wavfile import writefrom api_model import TransResult, Messagefrom .utils import log_blocklogger = getLogger("TranslatorApp")def save_to_wave(filename, data:np.ndarray, sample_rate=16000):write(filename, sample_rate, data)1 unmodified linedef __init__(self, size=2):self.history = collections.deque(maxlen=size)def _clean(self):self.history.clear()def add_entry(self, text, index):"""text: 文本17 unmodified lines# print("比较: ", text1, text2," => ", sim_12)# sim_23 = self.text_similarity(text2, text3)if sim_12 >= similarity_threshold:self._clean()return idx2return None49 unmodified linesself.commit_segment()class PywhisperInference:whisper_model = Nonellm_model = None# vad_model = None@classmethoddef initializer(cls, event:mp.Event, warmup=True):models_dir = config.MODEL_DIR.as_posix()cls.whisper_model = Model(model=config.WHISPER_MODEL,models_dir=models_dir,print_realtime=False,print_progress=False,print_timestamps=False,)if warmup:cls.warmup()# init llamacppcls.llm_model = QwenTranslator(config.LLM_MODEL_PATH, config.LLM_SYS_PROMPT)# cls.vad_model = VoiceActivityDetector()event.set()@classmethoddef init(cls):pass@classmethoddef warmup(cls, warmup_steps=1):mel, _, = soundfile.read("assets/jfk.flac")for _ in range(warmup_steps):cls.whisper_model.transcribe(mel, print_progress=False)@staticmethoddef config_language(language):if language == "zh":return config.MAX_LENTH_ZH, config.WHISPER_PROMPT_ZHelif language == "en":return config.MAX_LENGTH_EN, config.WHISPER_PROMPT_ENraise ValueError(f"Unsupported language : {language}")@classmethoddef transcribe(cls, audio_buffer, language):max_len, prompt = cls.config_language(language)audio_buffer = np.frombuffer(audio_buffer, dtype=np.float32)return cls.whisper_model.transcribe(audio_buffer,initial_prompt=prompt,language=language,token_timestamps=True,max_len=max_len)@classmethoddef translate(cls, context: str, src_lang, dst_lang):return cls.llm_model.translate(context, src_lang, dst_lang)# @classmethod# def voice_detect(cls, audio_buffer):# audio_buffer = np.frombuffer(audio_buffer, dtype=np.float32)# return cls.vad_model(audio_buffer)class PyWhiperCppServe(ServeClientBase):6 unmodified linesself._text_buffer = TripleTextBuffer()# 存储转录数据self._segment_manager = SegmentManager()self.lock = threading.Lock()self.frames_np = Noneself.sample_rate = 16000# self._audio_queue = Queue()# 进程初始化后再开始收音频self._ready_state = mp.Event()self._pool = PPool(max_workers=1,initializer=PywhisperInference.initializer,initargs=(self._ready_state,))self._pool.submit(PywhisperInference.init)logger.info('Create a process to process audio.')self.send_ready_state()# self.load_frame_thread = threading.Thread(target=self.load_frame_from_queue)# self.load_frame_thread.daemon = True# self.load_frame_thread.start()self.trans_thread = threading.Thread(target=self.speech_to_text)self.trans_thread.daemon = Trueself.trans_thread.start()def send_ready_state(self):self._ready_state.wait()self.websocket.send(json.dumps({"uid": self.client_uid,"message": self.SERVER_READY,4 unmodified linesself.language = src_langself.dst_lang = dst_lang# def load_frame_from_queue(self):# while True:# frame_np = self._audio_queue.get()# fut = self._pool.submit(PywhisperInference.voice_detect, frame_np.tobytes())# output = fut.result()# logger.info(f"VAD: {output}")# if output == True:# with self.lock:# if self.frames_np is None:# self.frames_np = frame_np.copy()# else:# self.frames_np = np.append(self.frames_np,frame_np)def add_frames(self, frame_np):# self._audio_queue.put(frame_np)with self.lock:18 unmodified lineslog_block("Audio buffer length", f"{audio_buffer.shape[0]/self.sample_rate:.2f}", "s")start_time = time.perf_counter()transcribe_fut = self._pool.submit(PywhisperInference.transcribe, audio_buffer.tobytes(), self.language)segments = transcribe_fut.result()log_block("Whisper transcrible time", f"{(time.perf_counter() - start_time):.3f}", "s")return segments4 unmodified lines# return "sample english"log_block("LLM translate input", f"{text}")start_time = time.perf_counter()translate_fut = self._pool.submit(PywhisperInference.translate, text, self.language, self.dst_lang)ret = translate_fut.result()log_block("LLM translate time", f"{(time.perf_counter() - start_time):.3f}", "s")return retdef _segments_split(self, segments, audio_buffer: np.ndarray):"""根据左边第一个标点符号来将序列拆分成 观察段 和 剩余部分"""40 unmodified linesreturn None, left_watch_string, right_watch_string, is_end_sentencedef speech_to_text(self):# c = 0while True:if self.exit:logger.info("Exiting speech to text thread")self._pool.shutdown(wait=False, cancel_futures=True)breakif self.frames_np is None:time.sleep(0.02) # wait for any audio to arrivecontinueaudio_buffer = self.get_audio_chunk_for_processing()# c+= 1# name = f"dev-{c}.wav"# save_to_wave(name, audio_buffer)try:# logger.info(f"Audio buffer length: {len(audio_buffer) / self.sample_rate:.2f}s")segments = self.transcribe_audio(audio_buffer)for tran_result in self.handle_transcription_output(segments, audio_buffer):self.send_to_client(tran_result)2 unmodified linesexcept Exception as e:logger.error(f"{e}")def handle_transcription_output(self, segments, audio_buffer):texts = "".join(i.text for i in segments)if not len(texts):63 unmodified linesreturn padded_audio.copy()def cleanup(self):logger.info("start shut down worker pool.")self._pool.shutdown(wait=False, cancel_futures=True)logger.info("shut down worker pool success.")return super().cleanup()#19 unmodified lines2021222324252627282930313233341 unmodified line36373839404117 unmodified lines5960616263646549 unmodified lines1151161171181191206 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481494 unmodified lines15415515615715815918 unmodified lines1781791801811821831841854 unmodified lines19019119219319419519619719840 unmodified lines2392402412422432442452462472482492502512522532542552562572582592602 unmodified lines26326426526626726863 unmodified lines33233333433519 unmodified linesfrom scipy.io.wavfile import writefrom api_model import TransResult, Messagefrom .utils import log_blockfrom .translatepipes import TranslatePipeslogger = getLogger("TranslatorApp")translate_pipes = TranslatePipes()translate_pipes.wait_ready()logger.info("Pipeline is ready.")def save_to_wave(filename, data:np.ndarray, sample_rate=16000):write(filename, sample_rate, data)1 unmodified linedef __init__(self, size=2):self.history = collections.deque(maxlen=size)def add_entry(self, text, index):"""text: 文本17 unmodified lines# print("比较: ", text1, text2," => ", sim_12)# sim_23 = self.text_similarity(text2, text3)if sim_12 >= similarity_threshold:self.history.clear()return idx2return None49 unmodified linesself.commit_segment()class PyWhiperCppServe(ServeClientBase):6 unmodified linesself._text_buffer = TripleTextBuffer()# 存储转录数据self._segment_manager = SegmentManager()self._ready_state = mp.Event()self.lock = threading.Lock()self.frames_np = Noneself.sample_rate = 16000# self._audio_queue = Queue()# 进程初始化后再开始收音频logger.info('Create a process to process audio.')self.send_ready_state()self.trans_thread = threading.Thread(target=self.speech_to_text)self.trans_thread.daemon = Trueself.trans_thread.start()def send_ready_state(self):# self._ready_state.wait()self.websocket.send(json.dumps({"uid": self.client_uid,"message": self.SERVER_READY,4 unmodified linesself.language = src_langself.dst_lang = dst_langdef add_frames(self, frame_np):# self._audio_queue.put(frame_np)with self.lock:18 unmodified lineslog_block("Audio buffer length", f"{audio_buffer.shape[0]/self.sample_rate:.2f}", "s")start_time = time.perf_counter()item = translate_pipes.transcrible(audio_buffer.tobytes(), self.language)segments = item.segmentslog_block("Whisper transcrible time", f"{(time.perf_counter() - start_time):.3f}", "s")return segments4 unmodified lines# return "sample english"log_block("LLM translate input", f"{text}")start_time = time.perf_counter()ret = translate_pipes.translate(text, self.language, self.dst_lang)log_block("LLM translate time", f"{(time.perf_counter() - start_time):.3f}", "s")return ret.translate_contentdef _segments_split(self, segments, audio_buffer: np.ndarray):"""根据左边第一个标点符号来将序列拆分成 观察段 和 剩余部分"""40 unmodified linesreturn None, left_watch_string, right_watch_string, is_end_sentencedef speech_to_text(self):c = 0while True:if self.exit:logger.info("Exiting speech to text thread")breakif self.frames_np is None:time.sleep(0.02) # wait for any audio to arrivecontinueaudio_buffer = self.get_audio_chunk_for_processing()# c+= 1# name = f"dev-{c}.wav"# save_to_wave(name, audio_buffer)try:logger.info(f"Audio buffer length: {len(audio_buffer) / self.sample_rate:.2f}s")segments = self.transcribe_audio(audio_buffer)for tran_result in self.handle_transcription_output(segments, audio_buffer):self.send_to_client(tran_result)2 unmodified linesexcept Exception as e:logger.error(f"{e}")def handle_transcription_output(self, segments, audio_buffer):texts = "".join(i.text for i in segments)if not len(texts):63 unmodified linesreturn padded_audio.copy()def cleanup(self):return super().cleanup()#
config.py+1
transcribe/pipelines/base.py+18-6
transcribe/pipelines/pipe_translate.py+1
transcribe/pipelines/pipe_whisper.py+1-1
transcribe/transcription.py+2-2
transcribe/translatepipes.py+11-13
transcribe/translator.py+2-8
transcribe/whisper.py+2-3
transcribe/whisper_llm_serve.py+18-112