SatyamSinghal commited on
Commit
dd9bab8
1 Parent(s): e20d1ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -6
app.py CHANGED
@@ -8,18 +8,21 @@ API_KEY = os.getenv("HF_API_KEY") # Fetch the API key from Hugging Face secrets
8
 
9
  headers = {"Authorization": f"Bearer {API_KEY}"}
10
 
11
- def generate_caption(image):
12
  """Queries the Hugging Face API to generate an image caption."""
13
  if not API_KEY:
14
  return "API key is missing! Please set it in Hugging Face secrets."
15
 
16
  try:
17
- response = requests.post(API_URL, headers=headers, files={"file": image})
18
- response.raise_for_status() # Raise an error for bad responses
19
- result = response.json()
20
- return result[0].get("generated_text", "No caption generated.")
 
21
  except requests.exceptions.RequestException as e:
22
  return f"Error: {str(e)}"
 
 
23
 
24
  # Gradio UI components
25
  title = "✨ Captionator_X ✨"
@@ -35,7 +38,7 @@ with gr.Blocks(theme=theme) as app:
35
 
36
  with gr.Row():
37
  with gr.Column():
38
- image_input = gr.Image(type="file", label="Upload Your Image", elem_id="image-uploader")
39
  with gr.Column():
40
  output_text = gr.Textbox(label="Generated Caption", lines=4, interactive=False, elem_id="output-text", placeholder="Your caption will appear here...")
41
 
 
8
 
9
  headers = {"Authorization": f"Bearer {API_KEY}"}
10
 
11
+ def generate_caption(image_path):
12
  """Queries the Hugging Face API to generate an image caption."""
13
  if not API_KEY:
14
  return "API key is missing! Please set it in Hugging Face secrets."
15
 
16
  try:
17
+ with open(image_path, "rb") as image_file:
18
+ response = requests.post(API_URL, headers=headers, files={"file": image_file})
19
+ response.raise_for_status() # Raise an error for bad responses
20
+ result = response.json()
21
+ return result[0].get("generated_text", "No caption generated.")
22
  except requests.exceptions.RequestException as e:
23
  return f"Error: {str(e)}"
24
+ except Exception as e:
25
+ return f"Error: {str(e)}"
26
 
27
  # Gradio UI components
28
  title = "✨ Captionator_X ✨"
 
38
 
39
  with gr.Row():
40
  with gr.Column():
41
+ image_input = gr.Image(type="filepath", label="Upload Your Image", elem_id="image-uploader")
42
  with gr.Column():
43
  output_text = gr.Textbox(label="Generated Caption", lines=4, interactive=False, elem_id="output-text", placeholder="Your caption will appear here...")
44