Spaces:
Runtime error
Runtime error
init commit
Browse files- app.py +52 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import requests
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
GRADIO_CALL_URL = "https://aliakr3m-embed-gen.hf.space/gradio_api/call/generate_embedding"
|
| 9 |
+
|
| 10 |
+
class EmbedRequest(BaseModel):
|
| 11 |
+
text: str
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@app.post("/embed")
|
| 15 |
+
def embed(req: EmbedRequest):
|
| 16 |
+
# Step 1: start Gradio job
|
| 17 |
+
r = requests.post(
|
| 18 |
+
GRADIO_CALL_URL,
|
| 19 |
+
json={"data": [req.text]},
|
| 20 |
+
headers={"Content-Type": "application/json"},
|
| 21 |
+
timeout=10,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
if r.status_code != 200:
|
| 25 |
+
raise HTTPException(500, "Failed to start embedding job")
|
| 26 |
+
|
| 27 |
+
event_id = r.json()["event_id"]
|
| 28 |
+
|
| 29 |
+
# Step 2: poll result (Gradio SSE, but we consume it here)
|
| 30 |
+
result_url = f"{GRADIO_CALL_URL}/{event_id}"
|
| 31 |
+
|
| 32 |
+
with requests.get(result_url, stream=True, timeout=30) as stream:
|
| 33 |
+
for line in stream.iter_lines():
|
| 34 |
+
if not line:
|
| 35 |
+
continue
|
| 36 |
+
|
| 37 |
+
decoded = line.decode()
|
| 38 |
+
|
| 39 |
+
if decoded.startswith("data:"):
|
| 40 |
+
payload = decoded[5:].strip()
|
| 41 |
+
|
| 42 |
+
# payload is JSON array:
|
| 43 |
+
# [
|
| 44 |
+
# "metadata string",
|
| 45 |
+
# [embedding floats...]
|
| 46 |
+
# ]
|
| 47 |
+
data = eval(payload) # controlled source
|
| 48 |
+
|
| 49 |
+
embedding = data[1]
|
| 50 |
+
return {"embedding": embedding}
|
| 51 |
+
|
| 52 |
+
raise HTTPException(500, "Embedding not completed")
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
requests
|
| 4 |
+
pydantic
|