Nafiul Huda commited on
Commit
b11fa6e
·
verified ·
1 Parent(s): 1515e5a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -249
app.py CHANGED
@@ -1,259 +1,48 @@
1
- import asyncio
2
- import re
3
  import os
4
- from threading import Thread
5
-
6
- import torch
7
  import gradio as gr
8
- import edge_tts
9
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
10
-
11
- # ──────────────────────────────────────────────────────────────────────────────
12
- # CONFIG
13
- # ──────────────────────────────────────────────────────────────────────────────
14
- MODEL_ID = "openbmb/MiniCPM5-1B"
15
- TTS_VOICE = "zh-CN-XiaoyiNeural"
16
- AUDIO_OUT = "/tmp/tts_output.mp3"
17
-
18
- # Use all available CPU cores
19
- CPU_THREADS = os.cpu_count() or 4
20
- torch.set_num_threads(CPU_THREADS)
21
- os.environ["OMP_NUM_THREADS"] = str(CPU_THREADS)
22
-
23
- # ──────────────────────────────────────────────────────────────────────────────
24
- # MODEL LOAD — CPU ONLY
25
- # ──────────────────────────────────────────────────────────────────────────────
26
- print("=" * 60)
27
- print(f" Loading MiniCPM5-1B on CPU ({CPU_THREADS} threads)")
28
- print("=" * 60)
29
-
30
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
31
-
32
- model = AutoModelForCausalLM.from_pretrained(
33
- MODEL_ID,
34
- torch_dtype = torch.float32, # CPU doesn't support bf16 efficiently
35
- device_map = "cpu", # force CPU
36
- trust_remote_code = True,
37
- low_cpu_mem_usage = True,
38
  )
39
- model.eval()
40
- print(f"[model] loaded on: {next(model.parameters()).device}")
41
- print(f"[model] using {CPU_THREADS} CPU threads")
42
-
43
-
44
- # ──────────────────────────────────────────────────────────────────────────────
45
- # TTS — persistent event loop (the version that worked)
46
- # ──────────────────────────────────────────────────────────────────────────────
47
- _tts_loop = None
48
-
49
- def _get_or_create_loop():
50
- global _tts_loop
51
- if _tts_loop is None or _tts_loop.is_closed():
52
- _tts_loop = asyncio.new_event_loop()
53
- return _tts_loop
54
-
55
- async def _tts_async(text: str, path: str):
56
- await edge_tts.Communicate(text, TTS_VOICE).save(path)
57
-
58
- def text_to_speech(text: str) -> str:
59
- loop = _get_or_create_loop()
60
- loop.run_until_complete(_tts_async(text, AUDIO_OUT))
61
- return AUDIO_OUT
62
 
 
 
 
 
 
 
 
63
 
64
- # ──────────────────────────────────────────────────────────────────────────────
65
- # INFERENCE — NO GPU, CPU ONLY
66
- # ──────────────────────────────────────────────────────────────────────────────
67
- def chat_and_speak(
68
- user_message: str,
69
- history: list,
70
- system_prompt: str,
71
- max_new_tokens: int,
72
- temperature: float,
73
- enable_thinking: bool,
74
- enable_tts: bool,
75
- ):
76
- if not user_message.strip():
77
- return history, history, None
78
 
79
- # Build messages
80
- messages = [{"role": "system", "content": system_prompt}]
81
- messages.extend(history)
82
- messages.append({"role": "user", "content": user_message})
83
-
84
- # Tokenize
85
- inputs = tokenizer.apply_chat_template(
86
- messages,
87
- tokenize = True,
88
- add_generation_prompt = True,
89
- enable_thinking = enable_thinking,
90
- return_dict = True,
91
- return_tensors = "pt",
92
- )
93
-
94
- # Streaming
95
- streamer = TextIteratorStreamer(
96
- tokenizer,
97
- skip_prompt = True,
98
- skip_special_tokens = True,
99
  )
100
-
101
- gen_kwargs = dict(
102
- **inputs,
103
- max_new_tokens = max_new_tokens,
104
- temperature = temperature,
105
- do_sample = temperature > 0,
106
- streamer = streamer,
107
- pad_token_id = tokenizer.eos_token_id,
108
- num_threads = CPU_THREADS, # ensure all threads are used
109
- )
110
-
111
- thread = Thread(target=model.generate, kwargs=gen_kwargs)
112
- thread.start()
113
-
114
- # Stream tokens
115
- partial_reply = ""
116
- current_history = history + [
117
- {"role": "user", "content": user_message},
118
- {"role": "assistant", "content": ""},
119
- ]
120
-
121
- for new_token in streamer:
122
- partial_reply += new_token
123
- current_history[-1]["content"] = partial_reply
124
- yield current_history, current_history, None
125
-
126
- thread.join()
127
-
128
- # Strip <think> blocks
129
- clean_reply = re.sub(
130
- r"<think>.*?</think>", "", partial_reply, flags=re.DOTALL
131
- ).strip()
132
-
133
- current_history[-1]["content"] = clean_reply
134
-
135
- # TTS
136
- audio_path = None
137
- if enable_tts and clean_reply:
138
- audio_path = text_to_speech(clean_reply)
139
-
140
- yield current_history, current_history, audio_path
141
-
142
-
143
- def clear_all():
144
- return [], [], None
145
-
146
-
147
- # ──────────────────────────────────────────────────────────────────────────────
148
- # UI
149
- # ──────────────────────────────────────────────────────────────────────────────
150
- with gr.Blocks(title="MiniCPM5-1B Chat") as demo:
151
-
152
- demo.theme = gr.themes.Soft()
153
- demo.css = "#chatbot{height:500px} footer{display:none!important}"
154
-
155
- gr.Markdown(
156
- r"""
157
- # 🤖 MiniCPM5-1B Chat (CPU-only)
158
- **Model:** `openbmb/MiniCPM5-1B` (FP32 · CPU) &nbsp;|&nbsp;
159
- **TTS Voice:** `zh-CN-XiaoyiNeural`
160
- """
161
  )
162
 
163
- with gr.Row():
164
- with gr.Column(scale=3):
165
- chatbot = gr.Chatbot(
166
- elem_id="chatbot",
167
- label="Conversation",
168
- height=500,
169
- )
170
- with gr.Row():
171
- user_input = gr.Textbox(
172
- placeholder="Type your message here…",
173
- label="Your message",
174
- lines=2,
175
- scale=5,
176
- )
177
- send_btn = gr.Button("Send 🚀", variant="primary", scale=1)
178
- clear_btn = gr.Button("🗑️ Clear conversation", variant="secondary")
179
- audio_out = gr.Audio(
180
- label="🔊 TTS Output (XiaoyiNeural)",
181
- type="filepath",
182
- autoplay=True,
183
- )
184
-
185
- with gr.Column(scale=1):
186
- gr.Markdown("### ⚙️ Settings")
187
-
188
- system_prompt = gr.Textbox(
189
- value="You are a helpful, friendly, and concise AI assistant.",
190
- label="💬 System Prompt",
191
- lines=3,
192
- info="Sets the assistant's personality",
193
- )
194
-
195
- max_new_tokens = gr.Slider(
196
- minimum=64,
197
- maximum=2048,
198
- value=512,
199
- step=64,
200
- label="📏 Max new tokens",
201
- )
202
-
203
- temperature = gr.Slider(
204
- minimum=0.1,
205
- maximum=2.0,
206
- value=0.7,
207
- step=0.05,
208
- label="🌡️ Temperature",
209
- info="Higher = more creative",
210
- )
211
-
212
- enable_thinking = gr.Checkbox(
213
- value=False,
214
- label="🧠 Enable Chain-of-Thought",
215
- info="Shows reasoning in <think> tags",
216
- )
217
-
218
- enable_tts = gr.Checkbox(
219
- value=True,
220
- label="🔊 Enable TTS",
221
- info="XiaoyiNeural voice",
222
- )
223
-
224
- gr.Markdown(
225
- f"""
226
- ---
227
- **Runtime:**
228
- - Device: CPU
229
- - Threads: {CPU_THREADS}
230
- - Model: FP32 (2.17 GB)
231
- - Voice: zh-CN-XiaoyiNeural
232
- """
233
- )
234
-
235
- state = gr.State([])
236
-
237
- for trigger in [send_btn.click, user_input.submit]:
238
- trigger(
239
- fn = chat_and_speak,
240
- inputs = [
241
- user_input,
242
- state,
243
- system_prompt,
244
- max_new_tokens,
245
- temperature,
246
- enable_thinking,
247
- enable_tts,
248
- ],
249
- outputs = [chatbot, state, audio_out],
250
- ).then(lambda: "", outputs=user_input)
251
-
252
- clear_btn.click(fn=clear_all, outputs=[chatbot, state, audio_out])
253
-
254
-
255
  if __name__ == "__main__":
256
- demo.queue(max_size=5).launch(
257
- server_name="0.0.0.0",
258
- server_port=7860,
259
- )
 
 
 
1
  import os
 
 
 
2
  import gradio as gr
3
+ import spaces
4
+ from huggingface_hub import hf_hub_download
5
+ from llama_cpp import Llama
6
+
7
+ # 1. Download GGUF model from Hub during startup
8
+ print("Downloading model...")
9
+ model_path = hf_hub_download(
10
+ repo_id="Abiray/MiniCPM5-1B-GGUF",
11
+ filename="minicpm5-1b-Q6_K.gguf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # 2. Initialize Llama.cpp with GPU layers enabled (n_gpu_layers=-1 sends all layers to GPU)
15
+ print("Initializing model on GPU paths...")
16
+ llm = Llama(
17
+ model_path=model_path,
18
+ n_ctx=2048,
19
+ n_gpu_layers=-1
20
+ )
21
 
22
+ # 3. Use the spaces decorator to temporarily claim the ZeroGPU instance for inference
23
+ @spaces.GPU(duration=60)
24
+ def generate_response(message, history):
25
+ # Construct an OpenAI/ChatML style prompt framework for MiniCPM
26
+ prompt = f"<|user|>\n{message}\n<|assistant|>\n"
 
 
 
 
 
 
 
 
 
27
 
28
+ # Run high-speed GPU accelerated inference
29
+ output = llm(
30
+ prompt,
31
+ max_tokens=256,
32
+ stop=["<|user|>", "<|assistant|>", "\n\n"],
33
+ echo=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  )
35
+
36
+ response_text = output["choices"][0]["text"].strip()
37
+ return response_text
38
+
39
+ # 4. Minimal, high-performance Gradio interface
40
+ with gr.Blocks(theme=gr.themes.Default(spacing_size="sm", radius_size="none")) as demo:
41
+ gr.Markdown("### MiniCPM-1B GGUF ZeroGPU Pipeline")
42
+ chatbot = gr.ChatInterface(
43
+ fn=generate_response,
44
+ type="messages"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  )
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  if __name__ == "__main__":
48
+ demo.launch(server_name="0.0.0.0", server_port=7860)