sldshrsdatabase / app.py
sldshr's picture
Update app.py
7b1ec46 verified
Raw History Blame Contribute Delete
1.75 kB
import os
import requests
import gradio as gr
from fastapi import Request
from fastapi.responses import HTMLResponse, JSONResponse
# 1. Читаем токен из секретов Спейса
HF_TOKEN = os.getenv("HF_TOKEN")
# Прокси-функция, которая прячет ключ на сервере
def proxy_to_hf(model, payload):
try:
headers = {
"Authorization": f"Bearer {HF_TOKEN}",
"Content-Type": "application/json"
}
response = requests.post(
f"https://huggingface.co{model}",
headers=headers,
json=payload
)
return response.json(), response.status_code
except Exception as e:
return {"error": str(e)}, 500
# Создаем стандартный интерфейс Gradio, чтобы Hugging Face не ругался
with gr.Blocks() as demo:
gr.Markdown("# Сервер скрытого прокси Hugging Face успешно запущен!")
# Забираем встроенный сервер FastAPI у Gradio
app = demo.app
# 2. Отдаем твой готовый HTML-сайт (аналог YouTube) на главной странице
@app.get("/", response_class=HTMLResponse)
def read_index():
with open("index.html", "r", encoding="utf-8") as f:
return f.read()
# 3. Безопасный эндпоинт, который принимает запросы от твоего index.html
@app.post("/api/proxy")
async def handle_proxy(request: Request):
body = await request.json()
model = body.get("model")
payload = body.get("payload")
result, status_code = proxy_to_hf(model, payload)
return JSONResponse(content=result, status_code=status_code)