Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,10 @@
|
|
| 1 |
-
|
| 2 |
from huggingface_hub import hf_hub_download
|
| 3 |
from llama_cpp import Llama
|
| 4 |
import time
|
| 5 |
-
import secrets
|
| 6 |
|
| 7 |
# ========================
|
| 8 |
-
# ১.
|
| 9 |
-
# ========================
|
| 10 |
-
app = Flask(__name__)
|
| 11 |
-
app.secret_key = secrets.token_hex(16)
|
| 12 |
-
|
| 13 |
-
# ========================
|
| 14 |
-
# ২. মডেল ডাউনলোড
|
| 15 |
# ========================
|
| 16 |
MODEL_REPO = "prism-ml/Bonsai-8B-gguf"
|
| 17 |
MODEL_FILE = "Bonsai-8B-Q1_0.gguf"
|
|
@@ -25,7 +18,7 @@ model_path = hf_hub_download(
|
|
| 25 |
print("✅ মডেল ডাউনলোড সম্পূর্ণ!")
|
| 26 |
|
| 27 |
# ========================
|
| 28 |
-
#
|
| 29 |
# ========================
|
| 30 |
llm = Llama(
|
| 31 |
model_path=model_path,
|
|
@@ -42,241 +35,75 @@ llm = Llama(
|
|
| 42 |
)
|
| 43 |
|
| 44 |
# ========================
|
| 45 |
-
#
|
| 46 |
# ========================
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
.chat-container {
|
| 57 |
-
max-width: 800px;
|
| 58 |
-
margin: 20px auto;
|
| 59 |
-
height: 80vh;
|
| 60 |
-
display: flex;
|
| 61 |
-
flex-direction: column;
|
| 62 |
-
}
|
| 63 |
-
.chat-messages {
|
| 64 |
-
flex: 1;
|
| 65 |
-
overflow-y: auto;
|
| 66 |
-
padding: 20px;
|
| 67 |
-
background: #f8f9fa;
|
| 68 |
-
border-radius: 10px;
|
| 69 |
-
margin-bottom: 20px;
|
| 70 |
-
}
|
| 71 |
-
.message {
|
| 72 |
-
margin-bottom: 15px;
|
| 73 |
-
padding: 10px 15px;
|
| 74 |
-
border-radius: 15px;
|
| 75 |
-
max-width: 80%;
|
| 76 |
-
word-wrap: break-word;
|
| 77 |
-
}
|
| 78 |
-
.user-message {
|
| 79 |
-
background: #0d6efd;
|
| 80 |
-
color: white;
|
| 81 |
-
margin-left: auto;
|
| 82 |
-
text-align: right;
|
| 83 |
-
}
|
| 84 |
-
.assistant-message {
|
| 85 |
-
background: #e9ecef;
|
| 86 |
-
color: #212529;
|
| 87 |
-
margin-right: auto;
|
| 88 |
-
}
|
| 89 |
-
.typing-indicator {
|
| 90 |
-
display: none;
|
| 91 |
-
padding: 10px 15px;
|
| 92 |
-
background: #e9ecef;
|
| 93 |
-
border-radius: 15px;
|
| 94 |
-
max-width: 80%;
|
| 95 |
-
margin-right: auto;
|
| 96 |
-
}
|
| 97 |
-
.typing-indicator span {
|
| 98 |
-
display: inline-block;
|
| 99 |
-
animation: blink 1.4s infinite both;
|
| 100 |
-
font-size: 20px;
|
| 101 |
-
}
|
| 102 |
-
.typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
|
| 103 |
-
.typing-indicator span:nth-child(3) { animation-delay: 0.4s; }
|
| 104 |
-
@keyframes blink {
|
| 105 |
-
0% { opacity: 0.1; }
|
| 106 |
-
20% { opacity: 1; }
|
| 107 |
-
100% { opacity: 0.1; }
|
| 108 |
-
}
|
| 109 |
-
.speed-info {
|
| 110 |
-
font-size: 12px;
|
| 111 |
-
color: #6c757d;
|
| 112 |
-
margin-top: 5px;
|
| 113 |
-
}
|
| 114 |
-
</style>
|
| 115 |
-
</head>
|
| 116 |
-
<body>
|
| 117 |
-
<div class="container chat-container">
|
| 118 |
-
<h1 class="text-center mb-4">🌳 Bonsai-8B Chat</h1>
|
| 119 |
-
<p class="text-center text-muted">⚡ ২-কোর CPU | ১৬ GB RAM | স্ট্রিমিং</p>
|
| 120 |
-
|
| 121 |
-
<div id="chat-messages" class="chat-messages">
|
| 122 |
-
<!-- মেসেজ এখানে আসবে -->
|
| 123 |
-
</div>
|
| 124 |
-
|
| 125 |
-
<div id="typing-indicator" class="typing-indicator">
|
| 126 |
-
<span>●</span><span>●</span><span>●</span>
|
| 127 |
-
</div>
|
| 128 |
-
|
| 129 |
-
<div class="input-group">
|
| 130 |
-
<input type="text" id="message-input" class="form-control" placeholder="আপনার প্রশ্ন লিখুন..." />
|
| 131 |
-
<button id="send-button" class="btn btn-primary">প্রেরণ</button>
|
| 132 |
-
<button id="clear-button" class="btn btn-outline-secondary">✕</button>
|
| 133 |
-
</div>
|
| 134 |
-
</div>
|
| 135 |
-
|
| 136 |
-
<script>
|
| 137 |
-
let chatHistory = [];
|
| 138 |
-
|
| 139 |
-
function addMessage(text, sender) {
|
| 140 |
-
const messagesDiv = document.getElementById('chat-messages');
|
| 141 |
-
const messageDiv = document.createElement('div');
|
| 142 |
-
messageDiv.className = `message ${sender}-message`;
|
| 143 |
-
messageDiv.innerHTML = text.replace(/\\n/g, '<br>');
|
| 144 |
-
messagesDiv.appendChild(messageDiv);
|
| 145 |
-
messagesDiv.scrollTop = messagesDiv.scrollHeight;
|
| 146 |
-
}
|
| 147 |
-
|
| 148 |
-
function showTyping() {
|
| 149 |
-
document.getElementById('typing-indicator').style.display = 'block';
|
| 150 |
-
document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight;
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
function hideTyping() {
|
| 154 |
-
document.getElementById('typing-indicator').style.display = 'none';
|
| 155 |
-
}
|
| 156 |
-
|
| 157 |
-
async function sendMessage() {
|
| 158 |
-
const input = document.getElementById('message-input');
|
| 159 |
-
const message = input.value.trim();
|
| 160 |
-
if (!message) return;
|
| 161 |
-
|
| 162 |
-
// ইউজার মেসেজ দেখান
|
| 163 |
-
addMessage(message, 'user');
|
| 164 |
-
chatHistory.push(['user', message]);
|
| 165 |
-
input.value = '';
|
| 166 |
-
|
| 167 |
-
// সেন্ড বাটন ডিজেবল করুন
|
| 168 |
-
document.getElementById('send-button').disabled = true;
|
| 169 |
-
|
| 170 |
-
// টাইপিং ইন্ডিকেটর দেখান
|
| 171 |
-
showTyping();
|
| 172 |
-
|
| 173 |
-
try {
|
| 174 |
-
const response = await fetch('/chat', {
|
| 175 |
-
method: 'POST',
|
| 176 |
-
headers: {
|
| 177 |
-
'Content-Type': 'application/json',
|
| 178 |
-
},
|
| 179 |
-
body: JSON.stringify({
|
| 180 |
-
message: message,
|
| 181 |
-
history: chatHistory
|
| 182 |
-
})
|
| 183 |
-
});
|
| 184 |
-
|
| 185 |
-
const data = await response.json();
|
| 186 |
-
hideTyping();
|
| 187 |
-
|
| 188 |
-
// অ্যাসিস্ট্যান্ট রেসপন্স দেখান
|
| 189 |
-
addMessage(data.response, 'assistant');
|
| 190 |
-
chatHistory.push(['assistant', data.response]);
|
| 191 |
-
|
| 192 |
-
// স্পিড তথ্য দেখান (ঐচ্ছিক)
|
| 193 |
-
if (data.speed) {
|
| 194 |
-
const speedInfo = document.createElement('div');
|
| 195 |
-
speedInfo.className = 'speed-info text-end';
|
| 196 |
-
speedInfo.textContent = `⚡ ${data.speed.toFixed(1)} tok/s | ${data.time.toFixed(1)}s`;
|
| 197 |
-
document.getElementById('chat-messages').appendChild(speedInfo);
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
} catch (error) {
|
| 201 |
-
hideTyping();
|
| 202 |
-
addMessage('❌ ত্রুটি: ' + error.message, 'assistant');
|
| 203 |
-
}
|
| 204 |
-
|
| 205 |
-
document.getElementById('send-button').disabled = false;
|
| 206 |
-
document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight;
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
-
function clearChat() {
|
| 210 |
-
document.getElementById('chat-messages').innerHTML = '';
|
| 211 |
-
chatHistory = [];
|
| 212 |
-
}
|
| 213 |
-
|
| 214 |
-
// এন্টার কী দিয়ে মেসেজ পাঠান
|
| 215 |
-
document.getElementById('message-input').addEventListener('keypress', (e) => {
|
| 216 |
-
if (e.key === 'Enter') sendMessage();
|
| 217 |
-
});
|
| 218 |
-
|
| 219 |
-
document.getElementById('send-button').addEventListener('click', sendMessage);
|
| 220 |
-
document.getElementById('clear-button').addEventListener('click', clearChat);
|
| 221 |
-
</script>
|
| 222 |
-
</body>
|
| 223 |
-
</html>
|
| 224 |
-
"""
|
| 225 |
-
|
| 226 |
-
# ========================
|
| 227 |
-
# ৫. Flask রাউট
|
| 228 |
-
# ========================
|
| 229 |
-
@app.route('/')
|
| 230 |
-
def index():
|
| 231 |
-
return render_template_string(HTML_TEMPLATE)
|
| 232 |
-
|
| 233 |
-
@app.route('/chat', methods=['POST'])
|
| 234 |
-
def chat():
|
| 235 |
-
data = request.json
|
| 236 |
-
message = data.get('message', '')
|
| 237 |
-
history = data.get('history', []) # [['user', 'msg'], ['assistant', 'resp']]
|
| 238 |
|
| 239 |
-
# ===== প্রম্পট তৈরি =====
|
| 240 |
prompt = ""
|
| 241 |
-
for
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
| 246 |
prompt += f"User: {message}\nAssistant:"
|
| 247 |
|
| 248 |
# ===== স্ট্রিমিং ইনফারেন্স =====
|
| 249 |
start_time = time.time()
|
| 250 |
-
response_text = ""
|
| 251 |
-
token_count = 0
|
| 252 |
|
|
|
|
| 253 |
stream = llm(
|
| 254 |
prompt,
|
| 255 |
max_tokens=256,
|
| 256 |
stop=["User:", "\n\n"],
|
| 257 |
echo=False,
|
| 258 |
-
stream=True,
|
| 259 |
)
|
| 260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
for chunk in stream:
|
| 262 |
if "choices" in chunk and len(chunk["choices"]) > 0:
|
| 263 |
delta = chunk["choices"][0].get("text", "")
|
| 264 |
if delta:
|
| 265 |
response_text += delta
|
| 266 |
token_count += 1
|
|
|
|
|
|
|
| 267 |
|
|
|
|
| 268 |
elapsed = time.time() - start_time
|
| 269 |
speed = token_count / elapsed if elapsed > 0 else 0
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
'speed': speed,
|
| 274 |
-
'time': elapsed,
|
| 275 |
-
'tokens': token_count
|
| 276 |
-
})
|
| 277 |
|
| 278 |
# ========================
|
| 279 |
-
#
|
| 280 |
# ========================
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
from huggingface_hub import hf_hub_download
|
| 3 |
from llama_cpp import Llama
|
| 4 |
import time
|
|
|
|
| 5 |
|
| 6 |
# ========================
|
| 7 |
+
# ১. মডেল ডাউনলোড
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# ========================
|
| 9 |
MODEL_REPO = "prism-ml/Bonsai-8B-gguf"
|
| 10 |
MODEL_FILE = "Bonsai-8B-Q1_0.gguf"
|
|
|
|
| 18 |
print("✅ মডেল ডাউনলোড সম্পূর্ণ!")
|
| 19 |
|
| 20 |
# ========================
|
| 21 |
+
# ২. LLM লোড করুন
|
| 22 |
# ========================
|
| 23 |
llm = Llama(
|
| 24 |
model_path=model_path,
|
|
|
|
| 35 |
)
|
| 36 |
|
| 37 |
# ========================
|
| 38 |
+
# ৩. চ্যাট ফাংশন (স্ট্রিমিং + সঠিক হিস্ট্রি)
|
| 39 |
# ========================
|
| 40 |
+
def generate_response(message, history):
|
| 41 |
+
"""
|
| 42 |
+
Gradio ChatInterface-এ history ফরম্যাট:
|
| 43 |
+
history = [
|
| 44 |
+
["user message 1", "assistant response 1"],
|
| 45 |
+
["user message 2", "assistant response 2"],
|
| 46 |
+
...
|
| 47 |
+
]
|
| 48 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ompt = ""
|
| 52 |
+
for item in history:
|
| 53 |
+
# history-এর প্রতিটি আইটেম একটি লিস্ট [user, assistant]
|
| 54 |
+
if isinstance(item, list) and len(item) >= 2:
|
| 55 |
+
prompt += f"User: {item[0]}\nAssistant: {item[1]}\n"
|
| 56 |
+
elif isinstance(item, tuple) and len(item) >= 2:
|
| 57 |
+
prompt += f"User: {item[0]}\nAssistant: {item[1]}\n"
|
| 58 |
+
|
| 59 |
prompt += f"User: {message}\nAssistant:"
|
| 60 |
|
| 61 |
# ===== স্ট্রিমিং ইনফারেন্স =====
|
| 62 |
start_time = time.time()
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
# স্ট্রিমিং জেনারেটর
|
| 65 |
stream = llm(
|
| 66 |
prompt,
|
| 67 |
max_tokens=256,
|
| 68 |
stop=["User:", "\n\n"],
|
| 69 |
echo=False,
|
| 70 |
+
stream=True, # স্ট্রিমিং চালু
|
| 71 |
)
|
| 72 |
|
| 73 |
+
# ===== টোকেন বাই টোকেন আউটপুট =====
|
| 74 |
+
response_text = ""
|
| 75 |
+
token_count = 0
|
| 76 |
+
|
| 77 |
for chunk in stream:
|
| 78 |
if "choices" in chunk and len(chunk["choices"]) > 0:
|
| 79 |
delta = chunk["choices"][0].get("text", "")
|
| 80 |
if delta:
|
| 81 |
response_text += delta
|
| 82 |
token_count += 1
|
| 83 |
+
# প্রতিটি টোকেন আপডেট (স্ট্রিমিং)
|
| 84 |
+
yield response_text + "▌" # কার্সর দেখানোর জন্য
|
| 85 |
|
| 86 |
+
# ===== ফাইনাল রেসপন্স (স্পিড মেট্রিক সহ) =====
|
| 87 |
elapsed = time.time() - start_time
|
| 88 |
speed = token_count / elapsed if elapsed > 0 else 0
|
| 89 |
|
| 90 |
+
final_response = f"{response_text}\n\n⚡ {speed:.1f} tok/s | {elapsed:.1f}s"
|
| 91 |
+
yield final_response
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
# ========================
|
| 94 |
+
# ৪. Gradio UI (স্ট্রিমিং সাপোর্ট সহ)
|
| 95 |
# ========================
|
| 96 |
+
with gr.Blocks(title="Bonsai-8B (CPU)") as demo:
|
| 97 |
+
gr.Markdown("""
|
| 98 |
+
# 🌳 Bonsai-8B Chat
|
| 99 |
+
### ⚡ ২-কোর CPU | ১৬ GB RAM | ১-বিট কোয়ান্টাইজড | স্ট্রিমিং
|
| 100 |
+
""")
|
| 101 |
+
|
| 102 |
+
chatbot = gr.ChatInterface(
|
| 103 |
+
fn=generate_response,
|
| 104 |
+
title="Bonsai-8B",
|
| 105 |
+
description="আপনার প্রশ্ন করুন... (টাইপিং ইফেক্ট দেখতে পাবেন)",
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
|