Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import logging
|
|
|
|
| 4 |
|
| 5 |
-
# 1. SUPRESSÃO DE RUÍDO NOS LOGS
|
|
|
|
| 6 |
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
|
| 7 |
logging.getLogger("gradio").setLevel(logging.ERROR)
|
|
|
|
| 8 |
|
| 9 |
# 2. CONFIGURAÇÃO CUDA ZERO-GPU
|
| 10 |
cuda_paths = [
|
|
@@ -40,11 +43,11 @@ import spaces
|
|
| 40 |
NGROK_TOKEN = os.getenv("NGROK_TOKEN")
|
| 41 |
|
| 42 |
MODEL_REGISTRY = {
|
| 43 |
-
"qwen2.5-coder-7b": {"repo_id": "Davizig10jojo/Qwen2.5-Coder-Mix-7B-GGUF", "filename": "Qwen2.5-Coder-Mix-7B-Q2_K.gguf", "min_size_mb": 1000},
|
| 44 |
-
"blazernano-0.6b": {"repo_id": "Davizig10jojo/BlazerNano-0.6b-GGUF", "filename": "blazernano-0.6b-Q6_K.gguf", "min_size_mb": 100},
|
| 45 |
"blazertiny-1b": {"repo_id": "Davizig10jojo/BlazerTiny-1b-GGUF", "filename": "blazertiny-1b-Q6_K.gguf", "min_size_mb": 200},
|
| 46 |
-
"
|
| 47 |
-
"
|
|
|
|
|
|
|
| 48 |
}
|
| 49 |
|
| 50 |
print("📥 Mapeando caminhos dos arquivos locais...")
|
|
@@ -52,7 +55,8 @@ MODEL_PATHS = {}
|
|
| 52 |
for key, meta in MODEL_REGISTRY.items():
|
| 53 |
try:
|
| 54 |
path = hf_hub_download(repo_id=meta["repo_id"], filename=meta["filename"])
|
| 55 |
-
if os.path.getsize(path) / (1024 * 1024) < meta["min_size_mb"]:
|
|
|
|
| 56 |
MODEL_PATHS[key] = path
|
| 57 |
print(f"📦 Arquivo pronto: {key}")
|
| 58 |
except Exception as e:
|
|
@@ -73,13 +77,15 @@ class ChatCompletionRequest(BaseModel):
|
|
| 73 |
stream: Optional[bool] = True
|
| 74 |
|
| 75 |
@spaces.GPU(duration=1)
|
| 76 |
-
def check_hf():
|
|
|
|
| 77 |
|
| 78 |
-
# 4. STREAMING
|
| 79 |
@spaces.GPU(duration=120)
|
| 80 |
def stream_generator(model_id: str, prompt_formatado: str, max_tokens: int, temperature: float):
|
| 81 |
from llama_cpp import Llama
|
| 82 |
|
|
|
|
| 83 |
if model_id not in MODEL_PATHS:
|
| 84 |
model_id = "blazertiny-1b"
|
| 85 |
|
|
@@ -96,15 +102,15 @@ def stream_generator(model_id: str, prompt_formatado: str, max_tokens: int, temp
|
|
| 96 |
use_mmap=True
|
| 97 |
)
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
stop_sequences = ["<|im_end|>", "</think>", "User:", "Assistant:"]
|
| 101 |
|
| 102 |
response_stream = llm(
|
| 103 |
prompt_formatado,
|
| 104 |
max_tokens=max_tokens,
|
| 105 |
temperature=temperature,
|
| 106 |
top_p=0.95,
|
| 107 |
-
repeat_penalty=1.
|
| 108 |
stop=stop_sequences,
|
| 109 |
echo=False,
|
| 110 |
stream=True
|
|
@@ -113,7 +119,7 @@ def stream_generator(model_id: str, prompt_formatado: str, max_tokens: int, temp
|
|
| 113 |
chunk_id = f"chatcmpl-{int(time.time())}"
|
| 114 |
for chunk in response_stream:
|
| 115 |
token = chunk["choices"][0]["text"]
|
| 116 |
-
if token and "</think>" not in token:
|
| 117 |
data = {
|
| 118 |
"id": chunk_id, "object": "chat.completion.chunk", "created": int(time.time()),
|
| 119 |
"model": model_id, "choices": [{"index": 0, "delta": {"content": token}, "finish_reason": None}]
|
|
@@ -124,22 +130,25 @@ def stream_generator(model_id: str, prompt_formatado: str, max_tokens: int, temp
|
|
| 124 |
yield "data: [DONE]\n"
|
| 125 |
|
| 126 |
except Exception as e:
|
| 127 |
-
print(f"🔴 Erro Crítico: {e}")
|
| 128 |
raise RuntimeError(str(e))
|
| 129 |
finally:
|
| 130 |
-
if llm:
|
|
|
|
| 131 |
gc.collect()
|
| 132 |
-
# Limpeza extra de VRAM
|
| 133 |
try:
|
| 134 |
import torch
|
| 135 |
-
if torch.cuda.is_available():
|
| 136 |
-
|
|
|
|
|
|
|
| 137 |
|
| 138 |
@api_app.post("/v1/chat/completions")
|
| 139 |
async def chat_completions(request: ChatCompletionRequest):
|
| 140 |
try:
|
| 141 |
-
#
|
| 142 |
-
system_prompt = "
|
|
|
|
| 143 |
prompt_formatado = f"<|im_start|>system\n{system_prompt}<|im_end|>\n"
|
| 144 |
|
| 145 |
for msg in request.messages:
|
|
@@ -149,10 +158,16 @@ async def chat_completions(request: ChatCompletionRequest):
|
|
| 149 |
prompt_formatado += "<|im_start|>assistant\n"
|
| 150 |
|
| 151 |
return StreamingResponse(
|
| 152 |
-
stream_generator(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
media_type="text/event-stream"
|
| 154 |
)
|
| 155 |
except Exception as e:
|
|
|
|
| 156 |
raise HTTPException(status_code=500, detail=str(e))
|
| 157 |
|
| 158 |
@api_app.get("/v1/models")
|
|
@@ -163,12 +178,15 @@ def run_fastapi():
|
|
| 163 |
uvicorn.run(api_app, host="127.0.0.1", port=8000, log_level="warning")
|
| 164 |
|
| 165 |
def iniciar_ngrok():
|
| 166 |
-
if not NGROK_TOKEN:
|
|
|
|
|
|
|
| 167 |
time.sleep(15)
|
| 168 |
ngrok.set_auth_token(NGROK_TOKEN)
|
| 169 |
for tentativa in range(5):
|
| 170 |
try:
|
| 171 |
-
ngrok.kill()
|
|
|
|
| 172 |
public_url = ngrok.connect(8000, proto="http", bind_tls=True)
|
| 173 |
print(f"\n🔗 URL POCKETPAL: {public_url.public_url}\n")
|
| 174 |
return
|
|
@@ -176,11 +194,13 @@ def iniciar_ngrok():
|
|
| 176 |
time.sleep(10)
|
| 177 |
|
| 178 |
with gr.Blocks() as demo:
|
| 179 |
-
gr.Markdown("# 🦏 Blazer API Hub [ZeroGPU
|
| 180 |
|
| 181 |
if __name__ == "__main__":
|
| 182 |
-
try:
|
| 183 |
-
|
|
|
|
|
|
|
| 184 |
threading.Thread(target=run_fastapi, daemon=True).start()
|
| 185 |
threading.Thread(target=iniciar_ngrok, daemon=True).start()
|
| 186 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import logging
|
| 4 |
+
import warnings
|
| 5 |
|
| 6 |
+
# 1. SUPRESSÃO TOTAL DE RUÍDO NOS LOGS
|
| 7 |
+
warnings.filterwarnings("ignore")
|
| 8 |
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
|
| 9 |
logging.getLogger("gradio").setLevel(logging.ERROR)
|
| 10 |
+
logging.getLogger("httpx").setLevel(logging.CRITICAL)
|
| 11 |
|
| 12 |
# 2. CONFIGURAÇÃO CUDA ZERO-GPU
|
| 13 |
cuda_paths = [
|
|
|
|
| 43 |
NGROK_TOKEN = os.getenv("NGROK_TOKEN")
|
| 44 |
|
| 45 |
MODEL_REGISTRY = {
|
|
|
|
|
|
|
| 46 |
"blazertiny-1b": {"repo_id": "Davizig10jojo/BlazerTiny-1b-GGUF", "filename": "blazertiny-1b-Q6_K.gguf", "min_size_mb": 200},
|
| 47 |
+
"blazerrhino-3b": {"repo_id": "Davizig10jojo/BlazerRhino-3B-GGUF", "filename": "BlazerRhino-3B-Instruct.Q4_K_M.gguf", "min_size_mb": 1000},
|
| 48 |
+
"blazernano-0.6b": {"repo_id": "Davizig10jojo/BlazerNano-0.6b-GGUF", "filename": "blazernano-0.6b-Q6_K.gguf", "min_size_mb": 100},
|
| 49 |
+
"qwen2.5-coder-7b": {"repo_id": "Davizig10jojo/Qwen2.5-Coder-Mix-7B-GGUF", "filename": "Qwen2.5-Coder-Mix-7B-Q2_K.gguf", "min_size_mb": 1000},
|
| 50 |
+
"blazerstandard-4b": {"repo_id": "Davizig10jojo/BlazerStandard-4B-GGUF", "filename": "blazerstandard-4b-Q6_K.gguf", "min_size_mb": 2000}
|
| 51 |
}
|
| 52 |
|
| 53 |
print("📥 Mapeando caminhos dos arquivos locais...")
|
|
|
|
| 55 |
for key, meta in MODEL_REGISTRY.items():
|
| 56 |
try:
|
| 57 |
path = hf_hub_download(repo_id=meta["repo_id"], filename=meta["filename"])
|
| 58 |
+
if os.path.getsize(path) / (1024 * 1024) < meta["min_size_mb"]:
|
| 59 |
+
raise Exception("Arquivo corrompido ou incompleto")
|
| 60 |
MODEL_PATHS[key] = path
|
| 61 |
print(f"📦 Arquivo pronto: {key}")
|
| 62 |
except Exception as e:
|
|
|
|
| 77 |
stream: Optional[bool] = True
|
| 78 |
|
| 79 |
@spaces.GPU(duration=1)
|
| 80 |
+
def check_hf():
|
| 81 |
+
return True
|
| 82 |
|
| 83 |
+
# 4. STREAMING OTIMIZADO
|
| 84 |
@spaces.GPU(duration=120)
|
| 85 |
def stream_generator(model_id: str, prompt_formatado: str, max_tokens: int, temperature: float):
|
| 86 |
from llama_cpp import Llama
|
| 87 |
|
| 88 |
+
# Fallback inteligente: se o modelo falhar ou não existir, usa o Tiny-1b que é mais estável
|
| 89 |
if model_id not in MODEL_PATHS:
|
| 90 |
model_id = "blazertiny-1b"
|
| 91 |
|
|
|
|
| 102 |
use_mmap=True
|
| 103 |
)
|
| 104 |
|
| 105 |
+
# Stops agressivos para evitar alucinação e vazamento de pensamento
|
| 106 |
+
stop_sequences = ["<|im_end|>", "</think>", "User:", "Assistant:", "I'm sorry", "I cannot"]
|
| 107 |
|
| 108 |
response_stream = llm(
|
| 109 |
prompt_formatado,
|
| 110 |
max_tokens=max_tokens,
|
| 111 |
temperature=temperature,
|
| 112 |
top_p=0.95,
|
| 113 |
+
repeat_penalty=1.15, # Penaliza repetições
|
| 114 |
stop=stop_sequences,
|
| 115 |
echo=False,
|
| 116 |
stream=True
|
|
|
|
| 119 |
chunk_id = f"chatcmpl-{int(time.time())}"
|
| 120 |
for chunk in response_stream:
|
| 121 |
token = chunk["choices"][0]["text"]
|
| 122 |
+
if token and "</think>" not in token and "<think>" not in token:
|
| 123 |
data = {
|
| 124 |
"id": chunk_id, "object": "chat.completion.chunk", "created": int(time.time()),
|
| 125 |
"model": model_id, "choices": [{"index": 0, "delta": {"content": token}, "finish_reason": None}]
|
|
|
|
| 130 |
yield "data: [DONE]\n"
|
| 131 |
|
| 132 |
except Exception as e:
|
| 133 |
+
print(f"🔴 Erro Crítico no Worker: {e}")
|
| 134 |
raise RuntimeError(str(e))
|
| 135 |
finally:
|
| 136 |
+
if llm:
|
| 137 |
+
del llm
|
| 138 |
gc.collect()
|
|
|
|
| 139 |
try:
|
| 140 |
import torch
|
| 141 |
+
if torch.cuda.is_available():
|
| 142 |
+
torch.cuda.empty_cache()
|
| 143 |
+
except:
|
| 144 |
+
pass
|
| 145 |
|
| 146 |
@api_app.post("/v1/chat/completions")
|
| 147 |
async def chat_completions(request: ChatCompletionRequest):
|
| 148 |
try:
|
| 149 |
+
# SYSTEM PROMPT BLINDADO: Força o português e proíbe recusas
|
| 150 |
+
system_prompt = "Você é o Blazer, um assistente prestativo. Responda SEMPRE em português brasileiro de forma direta, curta e natural. NUNCA diga que não entende ou peça mais informações. Apenas responda ao cumprimento ou pergunta."
|
| 151 |
+
|
| 152 |
prompt_formatado = f"<|im_start|>system\n{system_prompt}<|im_end|>\n"
|
| 153 |
|
| 154 |
for msg in request.messages:
|
|
|
|
| 158 |
prompt_formatado += "<|im_start|>assistant\n"
|
| 159 |
|
| 160 |
return StreamingResponse(
|
| 161 |
+
stream_generator(
|
| 162 |
+
model_id=request.model,
|
| 163 |
+
prompt_formatado=prompt_formatado,
|
| 164 |
+
max_tokens=request.max_tokens,
|
| 165 |
+
temperature=request.temperature
|
| 166 |
+
),
|
| 167 |
media_type="text/event-stream"
|
| 168 |
)
|
| 169 |
except Exception as e:
|
| 170 |
+
print(f"🔴 ERRO NA API: {e}")
|
| 171 |
raise HTTPException(status_code=500, detail=str(e))
|
| 172 |
|
| 173 |
@api_app.get("/v1/models")
|
|
|
|
| 178 |
uvicorn.run(api_app, host="127.0.0.1", port=8000, log_level="warning")
|
| 179 |
|
| 180 |
def iniciar_ngrok():
|
| 181 |
+
if not NGROK_TOKEN:
|
| 182 |
+
print("⚠️ NGROK_TOKEN ausente.")
|
| 183 |
+
return
|
| 184 |
time.sleep(15)
|
| 185 |
ngrok.set_auth_token(NGROK_TOKEN)
|
| 186 |
for tentativa in range(5):
|
| 187 |
try:
|
| 188 |
+
ngrok.kill()
|
| 189 |
+
time.sleep(3)
|
| 190 |
public_url = ngrok.connect(8000, proto="http", bind_tls=True)
|
| 191 |
print(f"\n🔗 URL POCKETPAL: {public_url.public_url}\n")
|
| 192 |
return
|
|
|
|
| 194 |
time.sleep(10)
|
| 195 |
|
| 196 |
with gr.Blocks() as demo:
|
| 197 |
+
gr.Markdown("# 🦏 Blazer API Hub [ZeroGPU Otimizado]")
|
| 198 |
|
| 199 |
if __name__ == "__main__":
|
| 200 |
+
try:
|
| 201 |
+
check_hf()
|
| 202 |
+
except:
|
| 203 |
+
pass
|
| 204 |
threading.Thread(target=run_fastapi, daemon=True).start()
|
| 205 |
threading.Thread(target=iniciar_ngrok, daemon=True).start()
|
| 206 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|