Nafiul Huda commited on
Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import gradio as grfrom llama_cpp import Llamaimport subprocessimport uuidimport os
# 1. Load the Model (Optimized for 2 vCPUs)# n_ctx is kept low (512) for speed since we aren't storing history.llm = Llama( model_path="model.gguf", n_threads=2, n_ctx=512, verbose=False)
def generate_response(user_input): # Format for Qwen (Single-shot, no history) prompt = f"<|im_start|>user\n{user_input}<|im_end|>\n<|im_start|>assistant\n" # Generate Text response = llm(prompt, max_tokens=150, stop=["<|im_end|>"]) text_output = response['choices'][0]['text'].strip() # Generate Audio using Piper audio_filename = f"/tmp/{uuid.uuid4()}.wav" # We pipe the text directly to the Piper binary # --fast reduces quality slightly but increases generation speed cmd = f"echo \"{text_output}\" | ./piper/piper --model voice.onnx --output_file {audio_filename}" subprocess.run(cmd, shell=True, check=True) return text_output, audio_filename
# 2. Build the Minimalist UI# Using a monochrome dark theme for a sleek, snappy feel.with gr.Blocks(theme=gr.themes.Monochrome()) as demo: gr.Markdown("## System: Online") with gr.Row(): with gr.Column(scale=3): user_text = gr.Textbox(placeholder="Enter command...", label="Input", lines=2) submit_btn = gr.Button("Execute", variant="primary") with gr.Column(scale=4): ai_text = gr.Textbox(label="Output", interactive=False, lines=4) ai_audio = gr.Audio(label="Voice", autoplay=True) # Connect UI to logic submit_btn.click( fn=generate_response, inputs=[user_text], outputs=[ai_text, ai_audio] ) # Allow pressing Enter to submit user_text.submit( fn=generate_response, inputs=[user_text], outputs=[ai_text, ai_audio] )
if __name__ == "__main__": # 0.0.0.0 is required for Docker/Hugging Face demo.launch(server_name="0.0.0.0", server_port=7860)app.pyAdded+64