danosethrus commited on
Commit
7709a3c
·
verified ·
1 Parent(s): 479b8fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -21
app.py CHANGED
@@ -1,16 +1,19 @@
1
  import os
2
- import requests
3
  from fastapi import FastAPI, Request
4
  from fastapi.responses import JSONResponse, HTMLResponse
 
5
 
6
  app = FastAPI()
7
 
8
- HF_TOKEN = os.environ.get("HF_TOKEN")
 
 
 
 
 
 
9
 
10
- # This is the modern 'Router' URL that is more reliable
11
- MODEL_URL = "https://router.huggingface.co/hf-inference/models/danosethrus/EthioDoc"
12
-
13
- @app.get("/", response_class=HTMLResponse)
14
  async def home():
15
  with open("index.html") as f:
16
  return f.read()
@@ -18,19 +21,8 @@ async def home():
18
  @app.post("/ask")
19
  async def ask_ai(request: Request):
20
  data = await request.json()
21
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
22
-
23
- # We send the question
24
- payload = {
25
- "inputs": data.get("inputs", ""),
26
- "options": {"wait_for_model": True}
27
- }
28
-
29
- response = requests.post(MODEL_URL, headers=headers, json=payload)
30
 
31
- # This checks if it's still 404 before trying to read JSON (to avoid the crash)
32
- if response.status_code != 200:
33
- print(f"FAILED: {response.status_code} - {response.text}")
34
- return JSONResponse({"error": "AI is still booting up or URL is wrong."}, status_code=response.status_code)
35
-
36
- return JSONResponse(content=response.json())
 
1
  import os
 
2
  from fastapi import FastAPI, Request
3
  from fastapi.responses import JSONResponse, HTMLResponse
4
+ from transformers import pipeline
5
 
6
  app = FastAPI()
7
 
8
+ # This loads the model directly into the Space's memory instead of calling an API
9
+ # NOTE: This might crash the Space if you don't have enough RAM!
10
+ try:
11
+ pipe = pipeline("text-generation", model="danosethrus/EthioDoc", device_map="auto")
12
+ except Exception as e:
13
+ pipe = None
14
+ print(f"Model Load Error: {e}")
15
 
16
+ @app.get("/")
 
 
 
17
  async def home():
18
  with open("index.html") as f:
19
  return f.read()
 
21
  @app.post("/ask")
22
  async def ask_ai(request: Request):
23
  data = await request.json()
24
+ if pipe is None:
25
+ return JSONResponse({"error": "Model failed to load in memory"}, status_code=500)
 
 
 
 
 
 
 
26
 
27
+ output = pipe(data.get("inputs", ""), max_new_tokens=100)
28
+ return JSONResponse(content=output)