Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223245 unmodified lines30313233343536373839404142434445464748495051525354555657585960616263646566672 unmodified lines7071727374757612 unmodified lines89909192939495969798991001011021031041051061074 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501512 unmodified linesimport sqlite3import loggingimport sysfrom fastapi import FastAPI, Depends, HTTPException, Securityfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom llama_cpp import Llama# --- CORS SETTINGS (This allows GitHub Pages to connect) ---app = FastAPI(title="Kwen Foundation Official API")# --- SECURE CORS SETTINGS ---# This ensures ONLY your GitHub Page can trigger the key generation and chatapp.add_middleware(CORSMiddleware,allow_origins=["https://hydrogenclient.github.io"],allow_credentials=True,allow_methods=["GET", "POST"], # Only allow the methods you actually useallow_headers=["*"],)5 unmodified lines)logger = logging.getLogger(__name__)# --- INITIALIZATION ---app = FastAPI(title="Kwen Foundation Official API",description="Secure API wrapper for Kwen-540M")security = HTTPBearer()MODEL_PATH = "kwen-v1-f16.gguf"DB_PATH = "keys.db"logger.info("--- Starting Kwen API Wrapper ---")# Check for model filelogger.info(f"Checking for model file at: {MODEL_PATH}")if not os.path.exists(MODEL_PATH):logger.error("CRITICAL: Model file not found! Check your Dockerfile wget command.")else:logger.info("Model file found.")# Initialize Kwen (The Kwen Foundation)try:logger.info("Loading Llama model into memory (this may take a moment)...")llm = Llama(model_path=MODEL_PATH,n_ctx=2048,n_threads=2, # Optimized for HF CPUsverbose=False)logger.info("Model loaded successfully.")except Exception as e:logger.error(f"Failed to load model: {str(e)}")# We don't raise here so the server can at least start and show the error in logsllm = None# --- DATABASE SETUP ---def init_db():2 unmodified linesconn.execute("CREATE TABLE IF NOT EXISTS keys (key TEXT PRIMARY KEY, user TEXT)")conn.commit()conn.close()logger.info("Database initialized successfully.")except Exception as e:logger.error(f"Database init failed: {str(e)}")12 unmodified linesuser = cur.fetchone()conn.close()if not user:logger.warning(f"Unauthorized access attempt.")raise HTTPException(status_code=403, detail="Invalid API Key")return user[0]# --- ENDPOINTS ---@app.get("/")def home():return {"status": "online" if llm else "model_error","model": "Kwen-540M","organization": "The Kwen Foundation","docs": "/docs"}@app.post("/admin/generate_key")4 unmodified linesconn.execute("INSERT INTO keys (key, user) VALUES (?, ?)", (new_key, username))conn.commit()conn.close()logger.info(f"Key generated for: {username}")return {"user": username, "key": new_key}except Exception as e:logger.error(f"Key generation failed: {str(e)}")raise HTTPException(status_code=500, detail="Database error")@app.post("/v1/chat")def chat(data: ChatInput, user=Depends(check_key)):if not llm:raise HTTPException(status_code=503, detail="Model not loaded")logger.info(f"Chat request from user: {user}")# ChatML formatting for Kwenformatted_prompt = f"<|im_start|>user\n{data.prompt}<|im_end|>\n<|im_start|>assistant\n"try:output = llm(formatted_prompt,max_tokens=data.max_tokens,temperature=data.temperature,stop=["<|im_end|>", "<|im_start|>"],echo=False)return {"response": output["choices"][0]["text"].strip(),"model": "kwen-540m","authorized_user": user}except Exception as e:logger.error(f"Inference error: {str(e)}")raise HTTPException(status_code=500, detail="Inference failed")if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)2 unmodified lines345678910111213141516171819202122232425262728295 unmodified lines35363738394041424344454647484950515253545556575859606162632 unmodified lines66676869707112 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251264 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531542 unmodified linesimport sqlite3import loggingimport sysimport jsonfrom fastapi import FastAPI, Depends, HTTPException, Securityfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom llama_cpp import Llama# --- INITIALIZATION ---app = FastAPI(title="Kwen Foundation Official API",description="Secure Streaming API wrapper for Kwen-540M")# --- SECURE CORS SETTINGS ---# Restricted to your specific GitHub Pages clientapp.add_middleware(CORSMiddleware,allow_origins=["https://hydrogenclient.github.io"],allow_credentials=True,allow_methods=["GET", "POST"],allow_headers=["*"],)5 unmodified lines)logger = logging.getLogger(__name__)security = HTTPBearer()MODEL_PATH = "kwen-v1-f16.gguf"DB_PATH = "keys.db"logger.info("--- Starting Kwen API Wrapper (Streaming Enabled) ---")# Check for model fileif not os.path.exists(MODEL_PATH):logger.error("CRITICAL: Model file not found!")llm = Noneelse:try:logger.info("Loading Llama model into memory...")llm = Llama(model_path=MODEL_PATH,n_ctx=2048,n_threads=2,verbose=False)logger.info("Model loaded successfully.")except Exception as e:logger.error(f"Failed to load model: {str(e)}")llm = None# --- DATABASE SETUP ---def init_db():2 unmodified linesconn.execute("CREATE TABLE IF NOT EXISTS keys (key TEXT PRIMARY KEY, user TEXT)")conn.commit()conn.close()except Exception as e:logger.error(f"Database init failed: {str(e)}")12 unmodified linesuser = cur.fetchone()conn.close()if not user:logger.warning("Unauthorized access attempt.")raise HTTPException(status_code=403, detail="Invalid API Key")return user[0]# --- STREAMING GENERATOR ---def generate_kwen_stream(prompt, max_tokens, temperature):"""Generates a stream of tokens from the Kwen model."""formatted_prompt = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"try:# Request stream from llama-cppstream = llm(formatted_prompt,max_tokens=max_tokens,temperature=temperature,stop=["<|im_end|>", "<|im_start|>"],stream=True)for chunk in stream:text = chunk["choices"][0]["text"]if text:# Format as a simple data string or SSE (Server-Sent Events)yield textexcept Exception as e:logger.error(f"Streaming error: {str(e)}")yield f"\n[Error: {str(e)}]"# --- ENDPOINTS ---@app.get("/")def home():return {"status": "online" if llm else "model_error","model": "Kwen-540M","organization": "The Kwen Foundation","client_restriction": "https://hydrogenclient.github.io"}@app.post("/admin/generate_key")4 unmodified linesconn.execute("INSERT INTO keys (key, user) VALUES (?, ?)", (new_key, username))conn.commit()conn.close()return {"user": username, "key": new_key}except Exception as e:logger.error(f"Key generation failed: {str(e)}")raise HTTPException(status_code=500, detail="Database error")@app.post("/v1/chat")async def chat(data: ChatInput, user=Depends(check_key)):if not llm:raise HTTPException(status_code=503, detail="Model not loaded")logger.info(f"Streaming request from user: {user}")return StreamingResponse(generate_kwen_stream(data.prompt, data.max_tokens, data.temperature),media_type="text/plain")if __name__ == "__main__":import uvicorn# Use standard port 7860 (common for HF Spaces)uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+59-56