Ashrafb commited on
Commit
1d48320
·
verified ·
1 Parent(s): a0dc8ce

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +27 -2
main.py CHANGED
@@ -2,6 +2,13 @@ from fastapi import FastAPI, File, UploadFile, Form, HTTPException
2
  from fastapi.responses import JSONResponse
3
  from gradio_client import Client
4
  import os
 
 
 
 
 
 
 
5
 
6
  app = FastAPI()
7
 
@@ -9,12 +16,30 @@ app = FastAPI()
9
  hf_token = os.environ.get('HF_TOKEN')
10
  client = Client("https://ashrafb-moondream1.hf.space/--replicas/o2fdl/")
11
 
12
- @app.post("/predict/")
13
- async def predict(image_path: str = Form(...), question: str = Form(...)):
14
  try:
15
  result = client.predict(image_path, question, api_name="/predict")
 
 
 
 
 
 
 
 
 
 
 
 
16
  return JSONResponse(content={"result": result})
17
  except Exception as e:
18
  error_msg = "An unexpected error occurred while processing the request."
19
  detail_msg = str(e)
20
  raise HTTPException(status_code=500, detail={"error": error_msg, "detail": detail_msg})
 
 
 
 
 
 
 
2
  from fastapi.responses import JSONResponse
3
  from gradio_client import Client
4
  import os
5
+ import tempfile
6
+ import shutil
7
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException
8
+ from fastapi.responses import HTMLResponse
9
+ from fastapi.staticfiles import StaticFiles
10
+ from fastapi.templating import Jinja2Templates
11
+ from fastapi.responses import FileResponse
12
 
13
  app = FastAPI()
14
 
 
16
  hf_token = os.environ.get('HF_TOKEN')
17
  client = Client("https://ashrafb-moondream1.hf.space/--replicas/o2fdl/")
18
 
19
+ # Function to generate captions for uploaded images
20
+ def get_caption(image_path: str, question: str):
21
  try:
22
  result = client.predict(image_path, question, api_name="/predict")
23
+ return result
24
+ except Exception as e:
25
+ error_msg = "Error occurred while generating caption: {}".format(str(e))
26
+ raise HTTPException(status_code=500, detail={"error": error_msg})
27
+
28
+ @app.post("/predict/")
29
+ async def predict(image: UploadFile = File(...), question: str = Form(...)):
30
+ try:
31
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_image:
32
+ shutil.copyfileobj(image.file, temp_image)
33
+ temp_image_path = temp_image.name
34
+ result = get_caption(temp_image_path, question)
35
  return JSONResponse(content={"result": result})
36
  except Exception as e:
37
  error_msg = "An unexpected error occurred while processing the request."
38
  detail_msg = str(e)
39
  raise HTTPException(status_code=500, detail={"error": error_msg, "detail": detail_msg})
40
+ app.mount("/", StaticFiles(directory="static", html=True), name="static")
41
+
42
+ @app.get("/")
43
+ def index() -> FileResponse:
44
+ return FileResponse(path="/app/static/index.html", media_type="text/html")
45
+