sinhal commited on
Commit
9fd60a8
Β·
verified Β·
1 Parent(s): a0f185c

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +59 -29
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
- # Load model from local file if exists, otherwise download from HF Hub
34
- if os.path.exists("./barbie.gguf"):
35
- print("Loading model from local path './barbie.gguf'...")
36
- model_path = "./barbie.gguf"
37
- elif os.path.exists("./static/barbie.gguf"):
38
- print("Loading model from './static/barbie.gguf'...")
39
- model_path = "./static/barbie.gguf"
40
- else:
41
- print(f"Downloading model {MODEL_FILENAME} from repo {REPO_ID} on HF Hub...")
42
  try:
43
- # Pass the token if present (necessary for private repos)
44
- token = os.getenv("HF_TOKEN")
45
- model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, token=token)
46
- print(f"Model downloaded successfully to: {model_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  except Exception as e:
48
- print(f"Error downloading from HF Hub: {e}")
49
- # Raise a clear error so uvicorn startup logs the issue immediately
50
- raise RuntimeError(f"Could not load GGUF model: {e}")
51
-
52
- print("Initializing Llama model...")
53
- llm = Llama(
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
- app.mount("/", StaticFiles(directory="static", html=True), name="static")
 
 
 
 
 
 
 
 
 
 
 
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")