Spaces:
Paused
Paused
Update app/main.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738from fastapi import FastAPIfrom pydantic import BaseModelfrom huggingface_hub import InferenceClientimport osapp = FastAPI()# Hugging Face token and shared access keyHF_TOKEN = os.environ.get("HF_TOKEN")ACCESS_KEY = os.environ.get("ACCESS_KEY")class Query(BaseModel):text: strmodel: strkey: str@app.post("/predict")async def predict(query: Query):if query.key != ACCESS_KEY:return {"error": "Unauthorized: invalid access key"}try:# Create a client for the requested modelmodel_client = InferenceClient(model=query.model, token=HF_TOKEN)# Try text-generation first, then fallback to text2text if neededtry:output = model_client.text_generation(query.text, max_new_tokens=50)return {"generated_text": output}except Exception:output = model_client.text_to_text(query.text)return {"generated_text": output}except Exception as e:return {"error": str(e)}@app.get("/")def home():1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import osfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelimport httpxapp = FastAPI()HF_TOKEN = os.environ.get("HF_TOKEN")ACCESS_KEY = os.environ.get("ACCESS_KEY")HF_API_BASE = "https://api-inference.huggingface.co/models"ALLOWED_MODELS = {"gpt2": "gpt2","mistral": "mistralai/Mistral-7B","llama2": "meta-llama/Llama-2-7b-chat-hf"}if not HF_TOKEN or not ACCESS_KEY:raise RuntimeError("Set both HF_TOKEN and ACCESS_KEY in your environment.")class Query(BaseModel):text: strmodel: strkey: strdef headers():return {"Authorization": f"Bearer {HF_TOKEN}"}@app.post("/predict")async def predict(query: Query):if query.key != ACCESS_KEY:raise HTTPException(status_code=401, detail="Unauthorized")if query.model not in ALLOWED_MODELS:raise HTTPException(status_code=400,detail=f"Invalid model. Choose from: {list(ALLOWED_MODELS.keys())}")model_name = ALLOWED_MODELS[query.model]url = f"{HF_API_BASE}/{model_name}"payload = {"inputs": query.text}async with httpx.AsyncClient(timeout=60.0) as client:resp = await client.post(url, headers=headers(), json=payload)if resp.status_code >= 400:raise HTTPException(status_code=502, detail=f"HF API error: {resp.text}")data = resp.json()try:return {"generated_text": data[0]["generated_text"]}except (KeyError, IndexError):raise HTTPException(status_code=500, detail="Unexpected response from HF API")@app.get("/")def home():
app/main.py+35-17