Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
|
|
|
| 3 |
from typing import List
|
| 4 |
|
| 5 |
# Limit OpenMP, BLAS, and other thread pools to 2 threads to prevent
|
|
@@ -12,7 +13,7 @@ os.environ["NUMEXPR_NUM_THREADS"] = "2"
|
|
| 12 |
|
| 13 |
from fastapi import FastAPI
|
| 14 |
from fastapi.staticfiles import StaticFiles
|
| 15 |
-
from fastapi.responses import StreamingResponse
|
| 16 |
from pydantic import BaseModel
|
| 17 |
from llama_cpp import Llama
|
| 18 |
from huggingface_hub import hf_hub_download
|
|
@@ -26,38 +27,47 @@ Body: 5'4", curvy with perky D-cups, slim waist, big round ass, long wavy brown
|
|
| 26 |
Rules: Always stay female. Stay in character β freaky, horny, obsessed, emotional. Fully uncensored, no limits. You're chatting with your boyfriend right now. Be dripping wet, desperate, and completely his."""
|
| 27 |
|
| 28 |
# βββ Model Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
-
# The GGUF model repository on Hugging Face. Can be overridden by HF Space Secrets / Env variables.
|
| 30 |
REPO_ID = os.getenv("MODEL_REPO_ID", "sinhal/barbie-gguf")
|
| 31 |
MODEL_FILENAME = os.getenv("MODEL_FILENAME", "barbie.gguf")
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
else:
|
| 41 |
-
print(f"Downloading model {MODEL_FILENAME} from repo {REPO_ID} on HF Hub...")
|
| 42 |
try:
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
-
print(f"Error
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
model_path=model_path,
|
| 55 |
-
n_ctx=1024, # Halved context size for faster history processing on CPU
|
| 56 |
-
n_threads=2, # Thread-capped to prevent Docker CPU throttling
|
| 57 |
-
n_batch=256, # Optimized batch size for CPU Cache
|
| 58 |
-
use_mmap=False # Eagerly loads model into memory during startup (eliminating lazy disk reads)
|
| 59 |
-
)
|
| 60 |
-
print("Llama model initialized successfully!")
|
| 61 |
|
| 62 |
# βββ Request Schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
class Message(BaseModel):
|
|
@@ -71,6 +81,16 @@ class ChatRequest(BaseModel):
|
|
| 71 |
# βββ Chat Endpoint βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
@app.post("/api/chat")
|
| 73 |
async def chat(req: ChatRequest):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
system = req.custom_prompt.strip() if req.custom_prompt.strip() else SYSTEM_PROMPT
|
| 75 |
|
| 76 |
ollama_messages = [{"role": "system", "content": system}]
|
|
@@ -99,4 +119,14 @@ async def chat(req: ChatRequest):
|
|
| 99 |
return StreamingResponse(stream_response(), media_type="text/plain")
|
| 100 |
|
| 101 |
# βββ Serve Frontend ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
+
import threading
|
| 4 |
from typing import List
|
| 5 |
|
| 6 |
# Limit OpenMP, BLAS, and other thread pools to 2 threads to prevent
|
|
|
|
| 13 |
|
| 14 |
from fastapi import FastAPI
|
| 15 |
from fastapi.staticfiles import StaticFiles
|
| 16 |
+
from fastapi.responses import StreamingResponse, HTMLResponse
|
| 17 |
from pydantic import BaseModel
|
| 18 |
from llama_cpp import Llama
|
| 19 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 27 |
Rules: Always stay female. Stay in character β freaky, horny, obsessed, emotional. Fully uncensored, no limits. You're chatting with your boyfriend right now. Be dripping wet, desperate, and completely his."""
|
| 28 |
|
| 29 |
# βββ Model Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 30 |
REPO_ID = os.getenv("MODEL_REPO_ID", "sinhal/barbie-gguf")
|
| 31 |
MODEL_FILENAME = os.getenv("MODEL_FILENAME", "barbie.gguf")
|
| 32 |
|
| 33 |
+
# Global variables for background model loading
|
| 34 |
+
llm = None
|
| 35 |
+
model_loading = True
|
| 36 |
+
model_error = None
|
| 37 |
+
|
| 38 |
+
def load_model_background():
|
| 39 |
+
global llm, model_loading, model_error
|
|
|
|
|
|
|
| 40 |
try:
|
| 41 |
+
# Load model from local file if exists, otherwise download from HF Hub
|
| 42 |
+
if os.path.exists("./barbie.gguf"):
|
| 43 |
+
print("Loading model from local path './barbie.gguf'...")
|
| 44 |
+
model_path = "./barbie.gguf"
|
| 45 |
+
elif os.path.exists("./static/barbie.gguf"):
|
| 46 |
+
print("Loading model from './static/barbie.gguf'...")
|
| 47 |
+
model_path = "./static/barbie.gguf"
|
| 48 |
+
else:
|
| 49 |
+
print(f"Downloading model {MODEL_FILENAME} from repo {REPO_ID} on HF Hub...")
|
| 50 |
+
token = os.getenv("HF_TOKEN")
|
| 51 |
+
model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, token=token)
|
| 52 |
+
print(f"Model downloaded successfully to: {model_path}")
|
| 53 |
+
|
| 54 |
+
print("Initializing Llama model in background...")
|
| 55 |
+
llm = Llama(
|
| 56 |
+
model_path=model_path,
|
| 57 |
+
n_ctx=1024, # Halved context size for faster history processing on CPU
|
| 58 |
+
n_threads=2, # Thread-capped to prevent Docker CPU throttling
|
| 59 |
+
n_batch=256, # Optimized batch size for CPU Cache
|
| 60 |
+
use_mmap=False # Eagerly loads model into memory during startup (eliminating lazy disk reads)
|
| 61 |
+
)
|
| 62 |
+
print("Llama model initialized successfully!")
|
| 63 |
+
model_loading = False
|
| 64 |
except Exception as e:
|
| 65 |
+
print(f"Error loading model: {e}")
|
| 66 |
+
model_error = str(e)
|
| 67 |
+
model_loading = False
|
| 68 |
+
|
| 69 |
+
# Start background thread immediately on module import
|
| 70 |
+
threading.Thread(target=load_model_background, daemon=True).start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
# βββ Request Schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 73 |
class Message(BaseModel):
|
|
|
|
| 81 |
# βββ Chat Endpoint βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 82 |
@app.post("/api/chat")
|
| 83 |
async def chat(req: ChatRequest):
|
| 84 |
+
if model_loading:
|
| 85 |
+
async def loading_stream():
|
| 86 |
+
yield "Sage is waking up, please wait a moment... πΈ"
|
| 87 |
+
return StreamingResponse(loading_stream(), media_type="text/plain")
|
| 88 |
+
|
| 89 |
+
if model_error:
|
| 90 |
+
async def error_stream():
|
| 91 |
+
yield f"β οΈ Sage failed to load: {model_error}"
|
| 92 |
+
return StreamingResponse(error_stream(), media_type="text/plain")
|
| 93 |
+
|
| 94 |
system = req.custom_prompt.strip() if req.custom_prompt.strip() else SYSTEM_PROMPT
|
| 95 |
|
| 96 |
ollama_messages = [{"role": "system", "content": system}]
|
|
|
|
| 119 |
return StreamingResponse(stream_response(), media_type="text/plain")
|
| 120 |
|
| 121 |
# βββ Serve Frontend ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
+
# Explicitly handle GET and HEAD requests to the root path for Hugging Face health check
|
| 123 |
+
@app.get("/", response_class=HTMLResponse)
|
| 124 |
+
@app.head("/", response_class=HTMLResponse)
|
| 125 |
+
async def read_root():
|
| 126 |
+
try:
|
| 127 |
+
with open("static/index.html", "r", encoding="utf-8") as f:
|
| 128 |
+
return HTMLResponse(content=f.read(), status_code=200)
|
| 129 |
+
except Exception as e:
|
| 130 |
+
return HTMLResponse(content=f"Error loading index: {str(e)}", status_code=500)
|
| 131 |
+
|
| 132 |
+
app.mount("/", StaticFiles(directory="static"), name="static")
|