prova / app.py
gg-insoore's picture
Update app.py
d7fde85 verified
from gradio_client import Client
from PIL import Image
import gradio as gr
import tempfile
import os
# Get Hugging Face Token from environment variables
# This token is crucial for accessing private spaces
HF_TOKEN = os.getenv("HF_TOKEN")
# 1️⃣ Connect to the private Space
# Ensure the URL is correct and the HF_TOKEN has permissions to access this private space.
client = Client("Insoore/damage_detector_insoore_gpu", hf_token=HF_TOKEN)
print("\n*** Private‑Space API ***")
# Print the API definition of the private space for debugging purposes
print(client.view_api())
print("*** end API print ***\n")
def call_private_api(pil_img: Image.Image):
"""
Calls the private damage detection API with the uploaded image and parameters.
Args:
pil_img (Image.Image): The input image uploaded by the user.
Returns:
Image.Image: The processed image with detected damages from the private API.
"""
# Save the user-uploaded image to a temporary JPEG file.
# This is necessary because gradio_client expects a file path for image inputs.
file_path = None # Initialize file_path
try:
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
pil_img.convert("RGB").save(tmp, "JPEG", quality=95)
file_path = tmp.name # Store the path to the temporary file
# DEBUG: Confirming type and value of file_path
print(f"DEBUG: Type of file_path: {type(file_path)}")
print(f"DEBUG: Value of file_path: {file_path}")
# Pass the file_path string directly as the image input.
# Temporarily removed all optional parameters to isolate the image input issue.
result_path = client.predict(
image=file_path, # Pass the file path directly as a string
api_name="/predict",
)
# result_path is a downloaded file path from the private API's output.
# Open this file and return it as a PIL Image.
return Image.open(result_path)
except Exception as e:
# Basic error handling: print the error and re-raise or return a placeholder
print(f"Error calling private API: {e}")
# In a real application, you might want to return a blank image or an error message
raise gr.Error(f"Failed to detect damages: {e}")
finally:
# Clean up the temporary file after the prediction
if file_path and os.path.exists(file_path):
os.remove(file_path)
# 3️⃣ Set up the Gradio interface for the public space
with gr.Blocks() as demo:
gr.Markdown("# Damage Detector")
gr.Markdown("Upload an image to detect damages using a private AI model.")
with gr.Row():
inp = gr.Image(type="pil", label="Upload an image of a vehicle")
out = gr.Image(type="pil", label="Detected damages highlighted")
# Button to trigger the API call
gr.Button("Detect Damages").click(
fn=call_private_api,
inputs=inp,
outputs=out,
api_name="detect_damages_public" # Optional: give a public API name for this function
)
# Launch the Gradio demo
# show_error=True will display exceptions in the UI
# share=True is for creating a public link (though Hugging Face Spaces handle this automatically)
demo.launch(show_error=True, share=True)