import gradio as gr import requests import base64 from PIL import Image import io import json import os # The target URL for the API endpoint API_URL = os.environ.get('PXiVision') def process_image(input_image: Image.Image): """ Takes a PIL Image, converts it to base64, sends it to an API, and returns the JSON response. Args: input_image: A PIL Image object from the Gradio input. Returns: A dictionary (JSON) from the API response or an error message. """ if input_image is None: return {"error": "Please upload an image first."} try: # Convert PIL Image to bytes with io.BytesIO() as byte_arr: input_image.save(byte_arr, format='JPEG') # You can change format if needed (e.g., PNG) image_bytes = byte_arr.getvalue() # Encode the bytes to a base64 string base64_image = base64.b64encode(image_bytes).decode("utf-8") # Prepare the request payload payload = { "image": base64_image } # Send the POST request to the API response = requests.post(API_URL, json=payload, timeout=60) # Added a 60-second timeout # Check if the request was successful response.raise_for_status() # This will raise an exception for HTTP errors (4xx, 5xx) # Return the JSON response from the API return response.json() except requests.exceptions.RequestException as e: # Handle network-related errors return {"error": f"API request failed: {e}"} except Exception as e: # Handle other potential errors (e.g., image processing) return {"error": f"An unexpected error occurred: {e}"} # --- Create the Gradio Interface --- # Define the input and output components for the interface image_input = gr.Image(type="pil", label="Upload National ID Image") json_output = gr.JSON(label="Extracted Information") # Create a descriptive title and description for the app title = "Egyptian National ID Extractor(Front)" description = """ Upload a clear image of an Egyptian National ID card. The application will send the image to a processing service and display the extracted information, such as name, address, and National ID number. """ # Assemble the interface demo = gr.Interface( fn=process_image, inputs=image_input, outputs=json_output, title=title, description=description, allow_flagging="never", examples=[ ['d1.jpg'] # Example image path ] ) # --- Launch the App --- if __name__ == "__main__": demo.launch()