Spaces:
Runtime error
Runtime error
David commited on
Commit ·
f12abfa
1
Parent(s): e9d25d8
Refactor text generation logic to use Hugging Face API and remove local model loading
Browse files
main.py
CHANGED
|
@@ -1,8 +1,13 @@
|
|
| 1 |
import os
|
| 2 |
from fastapi import FastAPI
|
| 3 |
from pydantic import BaseModel
|
| 4 |
-
from transformers import pipeline
|
| 5 |
from huggingface_hub import login
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Login if token is available (e.g., via Hugging Face Spaces secrets)
|
| 8 |
if "HF_TOKEN" in os.environ:
|
|
@@ -13,14 +18,9 @@ app = FastAPI()
|
|
| 13 |
class Prompt(BaseModel):
|
| 14 |
text: str
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
try:
|
| 20 |
-
generator = pipeline("text-generation", model="nvidia/gpt-oss-120b-Eagle3", use_auth_token=True)
|
| 21 |
-
except Exception:
|
| 22 |
-
# fallback to public model
|
| 23 |
-
generator = pipeline("text-generation", model="distilgpt2")
|
| 24 |
|
| 25 |
@app.get("/")
|
| 26 |
def read_root():
|
|
@@ -28,5 +28,13 @@ def read_root():
|
|
| 28 |
|
| 29 |
@app.post("/generate")
|
| 30 |
async def generate_text(prompt: Prompt):
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
from fastapi import FastAPI
|
| 3 |
from pydantic import BaseModel
|
|
|
|
| 4 |
from huggingface_hub import login
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
API_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 8 |
+
headers = {
|
| 9 |
+
"Authorization": f"Bearer {os.environ['HF_TOKEN']}",
|
| 10 |
+
}
|
| 11 |
|
| 12 |
# Login if token is available (e.g., via Hugging Face Spaces secrets)
|
| 13 |
if "HF_TOKEN" in os.environ:
|
|
|
|
| 18 |
class Prompt(BaseModel):
|
| 19 |
text: str
|
| 20 |
|
| 21 |
+
def query(payload):
|
| 22 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 23 |
+
return response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
@app.get("/")
|
| 26 |
def read_root():
|
|
|
|
| 28 |
|
| 29 |
@app.post("/generate")
|
| 30 |
async def generate_text(prompt: Prompt):
|
| 31 |
+
response = query({
|
| 32 |
+
"messages": [
|
| 33 |
+
{
|
| 34 |
+
"role": "user",
|
| 35 |
+
"content": prompt.text
|
| 36 |
+
}
|
| 37 |
+
],
|
| 38 |
+
"model": "meta-llama/Llama-3.2-3B-Instruct"
|
| 39 |
+
})
|
| 40 |
+
return {"response": response["choices"][0]["message"]}
|