Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import openai
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import io
|
| 5 |
+
import requests
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
# Load OpenAI API key (ensure it's securely set in your environment variables or Hugging Face secrets)
|
| 9 |
+
openai.api_key = os.getenv("OPENAI_API_KEY") # Replace with your API key if not using secrets
|
| 10 |
+
|
| 11 |
+
# Define the inference function to use OpenAI's gpt-image-1 model
|
| 12 |
+
def inference(input_image: Image.Image) -> Image.Image:
|
| 13 |
+
"""
|
| 14 |
+
Enhances the input handwritten sketch to a well-structured design using OpenAI's API.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
input_image: The input PIL Image (handwritten sketch).
|
| 18 |
+
|
| 19 |
+
Returns:
|
| 20 |
+
The output PIL Image (enhanced design).
|
| 21 |
+
"""
|
| 22 |
+
# Convert the PIL image to a byte array (required by the OpenAI API)
|
| 23 |
+
img_byte_arr = io.BytesIO()
|
| 24 |
+
input_image.save(img_byte_arr, format="PNG")
|
| 25 |
+
img_byte_arr = img_byte_arr.getvalue()
|
| 26 |
+
|
| 27 |
+
# Send the image to OpenAI's API with the prompt
|
| 28 |
+
try:
|
| 29 |
+
response = openai.Image.create(
|
| 30 |
+
prompt="Enhance this handwritten sketch to well-structured and computer-built design sketch.",
|
| 31 |
+
images=[img_byte_arr], # Attach the image
|
| 32 |
+
n=1, # Generate 1 result
|
| 33 |
+
size="1024x1024" # Specify the output image size
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Assuming the response contains a URL to the generated image (depending on OpenAI's API)
|
| 37 |
+
enhanced_image_url = response['data'][0]['url']
|
| 38 |
+
|
| 39 |
+
# Fetch the enhanced image from the URL
|
| 40 |
+
enhanced_image = Image.open(io.BytesIO(requests.get(enhanced_image_url).content))
|
| 41 |
+
return enhanced_image
|
| 42 |
+
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"Error during image enhancement: {e}")
|
| 45 |
+
return input_image # Return the original image if there's an error
|