Spaces:
Build error
Build error
Download app.py from Mirdehghan/Unity-Lumina-AI: direct link, hf CLI and curl.
- Browser
- Download file 6.94 kB
-
https://huggingface.co/spaces/Mirdehghan/Unity-Lumina-AI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Mirdehghan/Unity-Lumina-AI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Mirdehghan/Unity-Lumina-AI/resolve/main/app.py
6.94 kB
| import os | |
| import time | |
| import json | |
| from fastapi import FastAPI, Request | |
| from fastapi.responses import HTMLResponse, StreamingResponse | |
| from llama_cpp import Llama | |
| from huggingface_hub import hf_hub_download | |
| app = FastAPI() | |
| # --- تنظیمات مدل --- | |
| MODEL_REPO = "Dibachain/Diba-mini-GGUF" | |
| MODEL_FILE = "diba-mini-q4_k_m.gguf" | |
| MODEL_PATH = "model.gguf" | |
| # دانلود مدل در صورت عدم وجود (اولین اجرا) | |
| if not os.path.exists(MODEL_PATH): | |
| print("Downloading Diba-mini model...") | |
| hf_hub_download( | |
| repo_id=MODEL_REPO, | |
| filename=MODEL_FILE, | |
| local_dir=".", | |
| local_dir_use_symlinks=False | |
| ) | |
| os.rename(MODEL_FILE, MODEL_PATH) | |
| print("Model downloaded.") | |
| # بارگذاری مدل | |
| # n_threads=2 مطابق با CPU رایگان Spaces | |
| llm = Llama( | |
| model_path=MODEL_PATH, | |
| n_ctx=2048, | |
| n_threads=2, | |
| verbose=False | |
| ) | |
| # --- صفحه چت HTML در مسیر /test --- | |
| HTML_PAGE = """ | |
| <!DOCTYPE html> | |
| <html lang="fa" dir="rtl"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>تست سرعت Diba-mini</title> | |
| <style> | |
| body { font-family: Tahoma, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background: #f0f2f5; } | |
| #chat-box { background: white; border-radius: 10px; padding: 20px; height: 400px; overflow-y: auto; margin-bottom: 15px; border: 1px solid #ddd; } | |
| .message { margin-bottom: 15px; padding: 10px; border-radius: 8px; } | |
| .user { background: #e3f2fd; text-align: left; } | |
| .assistant { background: #f1f8e9; } | |
| .stats { font-size: 0.8em; color: #666; margin-top: 5px; border-top: 1px solid #eee; padding-top: 5px; } | |
| input { width: 80%; padding: 10px; border: 1px solid #ccc; border-radius: 5px; } | |
| button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; } | |
| button:disabled { background: #ccc; } | |
| </style> | |
| </head> | |
| <body> | |
| <h2>تست سرعت Diba-mini (توکن بر ثانیه)</h2> | |
| <div id="chat-box"></div> | |
| <div> | |
| <input type="text" id="user-input" placeholder="سوال خود را بنویسید..." onkeypress="if(event.key==='Enter') sendMessage()"> | |
| <button id="send-btn" onclick="sendMessage()">ارسال</button> | |
| </div> | |
| <div id="status" style="margin-top: 10px; color: #666;"></div> | |
| <script> | |
| const chatBox = document.getElementById('chat-box'); | |
| const userInput = document.getElementById('user-input'); | |
| const sendBtn = document.getElementById('send-btn'); | |
| const statusDiv = document.getElementById('status'); | |
| async function sendMessage() { | |
| const message = userInput.value.trim(); | |
| if (!message) return; | |
| // نمایش پیام کاربر | |
| addMessage('user', message); | |
| userInput.value = ''; | |
| sendBtn.disabled = true; | |
| // آمادهسازی پیام دستیار | |
| const assistantDiv = document.createElement('div'); | |
| assistantDiv.className = 'message assistant'; | |
| assistantDiv.innerHTML = '<em>در حال تولید...</em>'; | |
| chatBox.appendChild(assistantDiv); | |
| chatBox.scrollTop = chatBox.scrollHeight; | |
| const startTime = performance.now(); | |
| let tokenCount = 0; | |
| let fullText = ''; | |
| try { | |
| const response = await fetch('/api/chat', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ prompt: message }) | |
| }); | |
| const reader = response.body.getReader(); | |
| const decoder = new TextDecoder(); | |
| while (true) { | |
| const { done, value } = await reader.read(); | |
| if (done) break; | |
| const chunk = decoder.decode(value, { stream: true }); | |
| const lines = chunk.split('\\n\\n'); | |
| for (const line of lines) { | |
| if (line.startsWith('data: ')) { | |
| try { | |
| const data = JSON.parse(line.slice(6)); | |
| if (data.token) { | |
| fullText += data.token; | |
| tokenCount++; | |
| assistantDiv.innerHTML = fullText.replace(/\\n/g, '<br>'); | |
| chatBox.scrollTop = chatBox.scrollHeight; | |
| } | |
| } catch (e) { /* ignore parse errors */ } | |
| } | |
| } | |
| } | |
| const endTime = performance.now(); | |
| const durationSec = (endTime - startTime) / 1000; | |
| const tps = tokenCount / durationSec; | |
| // افزودن آمار سرعت | |
| const statsDiv = document.createElement('div'); | |
| statsDiv.className = 'stats'; | |
| statsDiv.textContent = `⏱️ زمان: ${durationSec.toFixed(2)}s | 🔢 توکن: ${tokenCount} | 🚀 سرعت: ${tps.toFixed(2)} tok/s`; | |
| assistantDiv.appendChild(statsDiv); | |
| } catch (error) { | |
| assistantDiv.innerHTML = 'خطا: ' + error.message; | |
| } finally { | |
| sendBtn.disabled = false; | |
| } | |
| } | |
| function addMessage(role, text) { | |
| const div = document.createElement('div'); | |
| div.className = 'message ' + role; | |
| div.textContent = text; | |
| chatBox.appendChild(div); | |
| chatBox.scrollTop = chatBox.scrollHeight; | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| async def chat_page(): | |
| return HTML_PAGE | |
| # --- API استریم برای چت --- | |
| async def chat_endpoint(request: Request): | |
| data = await request.json() | |
| user_prompt = data.get("prompt", "") | |
| # ساخت پرامپت با فرمت چت | |
| prompt = f"<|im_start|>system\nتو «دیبا» هستی، دستیار فارسی زبان.<|im_end|>\n<|im_start|>user\n{user_prompt}<|im_end|>\n<|im_start|>assistant\n" | |
| def stream_generator(): | |
| for output in llm( | |
| prompt, | |
| max_tokens=512, | |
| stream=True, | |
| stop=["<|im_end|>"], | |
| temperature=0.3 | |
| ): | |
| token = output.get("choices", [{}])[0].get("delta", {}).get("content", "") | |
| if token: | |
| # ارسال به فرمت SSE | |
| yield f"data: {json.dumps({'token': token})}\n\n" | |
| return StreamingResponse(stream_generator(), media_type="text/event-stream") | |
| async def root(): | |
| return {"status": "ok", "message": "به /test بروید برای تست چت و سرعت"} |