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

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +9 -38
main.py CHANGED
@@ -1,49 +1,20 @@
1
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
2
- from fastapi.responses import HTMLResponse, FileResponse
3
- from fastapi.staticfiles import StaticFiles
4
  from gradio_client import Client
5
  import os
6
- import tempfile
7
- import shutil
8
 
9
  app = FastAPI()
10
 
11
  # Initialize Gradio Client
12
  hf_token = os.environ.get('HF_TOKEN')
13
- client = Client("Ashrafb/moondream1", hf_token=hf_token)
14
 
15
- # Function to generate captions for uploaded images
16
- def get_caption(image, additional_context):
17
  try:
18
- if additional_context.strip():
19
- context = additional_context
20
- else:
21
- context = "What is this image? Describe this image to someone who is visually impaired."
22
- result = client.predict(image, context, 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("/uploadfile/")
29
- async def upload_file(image: UploadFile = File(...), additional_context: str = Form(...)):
30
- try:
31
- with tempfile.TemporaryDirectory() as temp_dir:
32
- temp_image_path = os.path.join(temp_dir, image.filename)
33
- with open(temp_image_path, "wb") as temp_image:
34
- shutil.copyfileobj(image.file, temp_image)
35
- with open(temp_image_path, "rb") as image_file:
36
- image_data = image_file.read()
37
- result = get_caption(image_data, additional_context)
38
- return {"result": result}
39
- except Exception as e:
40
- error_msg = "Error occurred while processing image: {}".format(str(e))
41
- raise HTTPException(status_code=500, detail={"error": error_msg})
42
-
43
- # Serve static files
44
- app.mount("/", StaticFiles(directory="static", html=True), name="static")
45
-
46
- # Serve index.html
47
- @app.get("/")
48
- def index() -> FileResponse:
49
- return FileResponse(path="/app/static/index.html", media_type="text/html")
 
1
  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
 
8
  # Initialize Gradio Client
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})