Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from fastapi import FastAPI, Depends, HTTPException
|
| 3 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 4 |
+
from transformers import pipeline, AutoTokenizer
|
| 5 |
+
import torch
|
| 6 |
+
import jwt
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from typing import List, Dict, Optional
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
|
| 13 |
+
load_dotenv()
|
| 14 |
+
SECRET_KEY = os.getenv('SECRET_KEY')
|
| 15 |
+
security = HTTPBearer()
|
| 16 |
+
|
| 17 |
+
app = FastAPI()
|
| 18 |
+
|
| 19 |
+
model_name = 'Qwen/Qwen3-0.6B'
|
| 20 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 21 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 22 |
+
pipe = pipeline('text-generation', model=model_name, device=device, trust_remote_code=True)
|
| 23 |
+
|
| 24 |
+
class GenerateRequest(BaseModel):
|
| 25 |
+
messages: List[Dict[str, str]]
|
| 26 |
+
enable_thinking: Optional[bool] = False
|
| 27 |
+
|
| 28 |
+
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 29 |
+
try:
|
| 30 |
+
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=['HS256'])
|
| 31 |
+
return payload
|
| 32 |
+
except Exception as e:
|
| 33 |
+
raise HTTPException(status_code=401, detail=str(e))
|
| 34 |
+
|
| 35 |
+
@app.post('/generate')
|
| 36 |
+
def generate(req: GenerateRequest, user=Depends(verify_token)):
|
| 37 |
+
try:
|
| 38 |
+
prompt = tokenizer.apply_chat_template(req.messages, tokenize=False, add_generation_prompt=True)
|
| 39 |
+
result = pipe(prompt, max_new_tokens=200)
|
| 40 |
+
full_text = result[0]['generated_text']
|
| 41 |
+
|
| 42 |
+
# Extract assistant response
|
| 43 |
+
response_split = full_text.split('<|im_start|>assistant')
|
| 44 |
+
content = response_split[-1] if len(response_split) > 1 else full_text
|
| 45 |
+
|
| 46 |
+
# Handle thinking block based on flag
|
| 47 |
+
if not req.enable_thinking:
|
| 48 |
+
content = re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL)
|
| 49 |
+
|
| 50 |
+
clean_response = content.replace('<|im_end|>', '').strip()
|
| 51 |
+
|
| 52 |
+
return {'generated_text': clean_response}
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return {'error': str(e)}
|
| 55 |
+
|
| 56 |
+
if __name__ == '__main__':
|
| 57 |
+
import uvicorn
|
| 58 |
+
uvicorn.run(app, host='0.0.0.0', port=8000)
|