monate615 commited on
Commit
2f2fb3b
verified
1 Parent(s): a57df1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -13
app.py CHANGED
@@ -4,9 +4,11 @@ from PIL import Image
4
  import io
5
  import gradio as gr
6
  import requests
 
 
7
 
8
- # Load OpenAI API key from environment variable (set this in your Hugging Face Space Secrets or environment)
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 DALL路E model or another image model
12
  def inference(input_image: Image.Image) -> Image.Image:
@@ -25,20 +27,23 @@ def inference(input_image: Image.Image) -> Image.Image:
25
  img_byte_arr = img_byte_arr.getvalue()
26
 
27
  try:
28
- # Send the image to OpenAI's API to edit/enhance the image with a prompt
29
- response = openai.Image.create_edit(
30
- image=img_byte_arr,
31
- mask=None, # In case you have a mask image, otherwise set this to None
32
- prompt="Enhance this handwritten sketch to well-structured and computer-built design sketch.",
33
- n=1, # Generate 1 result
34
- size="1024x1024" # Specify the output image size
 
 
 
35
  )
36
-
37
- # Fetch the enhanced image URL from the response
38
- enhanced_image_url = response['data'][0]['url']
39
 
40
  # Download the image from the URL and open it with PIL
41
- enhanced_image = Image.open(io.BytesIO(requests.get(enhanced_image_url).content))
42
 
43
  return enhanced_image
44
 
 
4
  import io
5
  import gradio as gr
6
  import requests
7
+ import base64
8
+ from openai import OpenAI
9
 
10
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
11
+ client = OpenAI(api_key=OPENAI_API_KEY)
12
 
13
  # Define the inference function to use OpenAI's DALL路E model or another image model
14
  def inference(input_image: Image.Image) -> Image.Image:
 
27
  img_byte_arr = img_byte_arr.getvalue()
28
 
29
  try:
30
+ prompt = """
31
+ Enhance this handwritten sketch to well-structured and computer-built design sketch.
32
+ """
33
+
34
+ result = client.images.edit(
35
+ model="gpt-image-1",
36
+ image=[
37
+ img_byte_arr,
38
+ ],
39
+ prompt=prompt
40
  )
41
+
42
+ image_base64 = result.data[0].b64_json
43
+ image_bytes = base64.b64decode(image_base64)
44
 
45
  # Download the image from the URL and open it with PIL
46
+ enhanced_image = Image.open(image_bytes)
47
 
48
  return enhanced_image
49