Luisgust commited on
Commit
f609e95
·
verified ·
1 Parent(s): 565d4ff

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +8 -11
main.py CHANGED
@@ -1,37 +1,34 @@
1
  import os
2
  from fastapi import FastAPI, File, UploadFile, Form
3
  from fastapi.responses import JSONResponse
4
-
5
  from gradio_client import Client, handle_file
6
 
7
  app = FastAPI()
8
 
9
-
10
-
11
-
12
  HF_TOKEN = os.getenv("HF_TOKEN")
 
 
13
 
14
- # Initialize the Gradio client with the token
15
- client = Client("Luisgust/moondream1", hf_token=HF_TOKEN)
 
 
 
16
 
17
  @app.post("/get_caption")
18
  async def get_caption(image: UploadFile = File(...), context: str = Form(...)):
19
  try:
20
- # Read the uploaded image file
21
  contents = await image.read()
22
-
23
- # Use handle_file to prepare the image for the Gradio client
24
  image_data = handle_file(contents, orig_name=image.filename)
25
 
26
- # Call the Gradio API
27
  result = client.predict(
28
  image=image_data,
29
  question=context,
30
  api_name="/answer_question"
31
  )
32
 
33
- # Return the result as a JSON response
34
  return JSONResponse(content={"caption": result})
35
  except Exception as e:
 
36
  return JSONResponse(content={"error": str(e)}, status_code=500)
37
 
 
1
  import os
2
  from fastapi import FastAPI, File, UploadFile, Form
3
  from fastapi.responses import JSONResponse
 
4
  from gradio_client import Client, handle_file
5
 
6
  app = FastAPI()
7
 
 
 
 
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
+ if not HF_TOKEN:
10
+ raise ValueError("HF_TOKEN environment variable is not set.")
11
 
12
+ try:
13
+ client = Client("Luisgust/moondream1", hf_token=HF_TOKEN)
14
+ except Exception as e:
15
+ print(f"Failed to initialize Gradio client: {e}")
16
+ raise
17
 
18
  @app.post("/get_caption")
19
  async def get_caption(image: UploadFile = File(...), context: str = Form(...)):
20
  try:
 
21
  contents = await image.read()
 
 
22
  image_data = handle_file(contents, orig_name=image.filename)
23
 
 
24
  result = client.predict(
25
  image=image_data,
26
  question=context,
27
  api_name="/answer_question"
28
  )
29
 
 
30
  return JSONResponse(content={"caption": result})
31
  except Exception as e:
32
+ print(f"Error during prediction: {e}")
33
  return JSONResponse(content={"error": str(e)}, status_code=500)
34