EntropyDrop commited on
Commit
2add930
·
1 Parent(s): 5b6eed5

feat: gpt skin2real

Browse files
Files changed (4) hide show
  1. .gitignore +1 -0
  2. gpt_image.py +208 -0
  3. gpt_sim2real.py +23 -0
  4. gpt_skin2real.py +130 -0
.gitignore CHANGED
@@ -1,2 +1,3 @@
1
  preserved
2
  __pycache__
 
 
1
  preserved
2
  __pycache__
3
+ .env
gpt_image.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ import uuid
5
+ import requests
6
+ import boto3
7
+ import mimetypes
8
+ from dotenv import load_dotenv
9
+
10
+ # Load .env file from the current directory
11
+ env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
12
+ load_dotenv(env_path)
13
+
14
+ # Retrieve configuration details
15
+ AWS_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
16
+ AWS_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")
17
+ AWS_REGION = os.getenv("AWS_REGION")
18
+ AWS_BUCKET_NAME = os.getenv("AWS_BUCKET_NAME")
19
+ GPT_IMAGE_API_BASE_URL = os.getenv("GPT_IMAGE_API_BASE_URL")
20
+ API_KEY = os.getenv("API_KEY")
21
+
22
+ def upload_file_to_s3(local_path, bucket, key):
23
+ """
24
+ Upload a local file to S3 with ACL='public-read' so the external API can access it.
25
+ """
26
+ print(f"[*] Uploading '{local_path}' to S3 bucket '{bucket}' with key '{key}'...")
27
+ s3_client = boto3.client(
28
+ 's3',
29
+ aws_access_key_id=AWS_ACCESS_KEY_ID,
30
+ aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
31
+ region_name=AWS_REGION
32
+ )
33
+
34
+ # Guess mime type or default to image/png
35
+ content_type, _ = mimetypes.guess_type(local_path)
36
+ if not content_type:
37
+ content_type = 'image/png'
38
+
39
+ s3_client.upload_file(
40
+ local_path,
41
+ bucket,
42
+ key,
43
+ ExtraArgs={'ACL': 'public-read', 'ContentType': content_type}
44
+ )
45
+
46
+ s3_url = f"https://{bucket}.s3.{AWS_REGION}.amazonaws.com/{key}"
47
+ print(f"[+] Uploaded successfully. S3 public URL: {s3_url}")
48
+ return s3_url
49
+
50
+ def generate_image(s3_urls, prompt):
51
+ """
52
+ Triggers the image-to-image task using the gpt-image-2 model.
53
+ """
54
+ url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/generate"
55
+ payload = {
56
+ "model": "gpt-image-2",
57
+ "params": {
58
+ "aspect_ratio": "1:1",
59
+ "images": s3_urls,
60
+ "n": 1,
61
+ "quality": "auto",
62
+ "resolution": "1K",
63
+ "response_format": "url",
64
+ "size": "auto"
65
+ },
66
+ "prompt": prompt
67
+ }
68
+
69
+ headers = {"Content-Type": "application/json"}
70
+ if API_KEY:
71
+ headers["Authorization"] = f"Bearer {API_KEY}"
72
+
73
+ print(f"[*] Sending image generation request to: {url}")
74
+ response = requests.post(url, json=payload, headers=headers)
75
+ response.raise_for_status()
76
+ res_json = response.json()
77
+
78
+ # Try parsing task_id from root or nested "data" dictionary
79
+ task_id = res_json.get("task_id")
80
+ if not task_id and "data" in res_json and isinstance(res_json["data"], dict):
81
+ task_id = res_json["data"].get("task_id")
82
+
83
+ if not task_id:
84
+ raise ValueError(f"Failed to obtain task_id from response: {res_json}")
85
+ print(f"[+] Task created successfully. Task ID: {task_id}")
86
+ return task_id
87
+
88
+ def poll_task_status(task_id, timeout_seconds=120, poll_interval=5):
89
+ """
90
+ Polls the task status with a timeout.
91
+ """
92
+ status_url = f"{GPT_IMAGE_API_BASE_URL}/v1/media/status"
93
+ start_time = time.time()
94
+ print(f"[*] Polling task status (timeout={timeout_seconds}s, interval={poll_interval}s)...")
95
+
96
+ while True:
97
+ elapsed = time.time() - start_time
98
+ if elapsed > timeout_seconds:
99
+ raise TimeoutError(f"Task {task_id} timed out after {timeout_seconds} seconds.")
100
+
101
+ try:
102
+ headers = {}
103
+ if API_KEY:
104
+ headers["Authorization"] = f"Bearer {API_KEY}"
105
+ response = requests.get(status_url, params={"task_id": task_id}, headers=headers)
106
+ response.raise_for_status()
107
+ res_json = response.json()
108
+
109
+ # Support both flat and nested responses for task status
110
+ data = res_json
111
+ if "data" in res_json and isinstance(res_json["data"], dict):
112
+ if any(k in res_json["data"] for k in ["state", "is_final", "result_url"]):
113
+ data = res_json["data"]
114
+
115
+ state = data.get("state")
116
+ is_final = data.get("is_final", False)
117
+ progress = data.get("progress", "0%")
118
+ print(f"[*] [Elapsed: {int(elapsed)}s] State: {state}, Progress: {progress}")
119
+
120
+ if is_final:
121
+ if state == "success":
122
+ result_url = data.get("result_url")
123
+ if not result_url:
124
+ raise ValueError("Task finished with success state, but result_url is empty.")
125
+ return result_url
126
+ else:
127
+ error_msg = data.get("error", "Unknown error")
128
+ raise RuntimeError(f"Task failed with state '{state}': {error_msg}")
129
+
130
+ except Exception as e:
131
+ # Print error and retry during polling
132
+ print(f"[!] Error querying task status: {e}")
133
+
134
+ time.sleep(poll_interval)
135
+
136
+ def download_image(url, output_path):
137
+ """
138
+ Downloads the final image from the given URL and saves it locally.
139
+ """
140
+ print(f"[*] Downloading result image from: {url}")
141
+ response = requests.get(url, stream=True)
142
+ response.raise_for_status()
143
+ with open(output_path, "wb") as f:
144
+ for chunk in response.iter_content(chunk_size=8192):
145
+ f.write(chunk)
146
+ print(f"[+] Image saved successfully to: {output_path}")
147
+
148
+ def delete_file_from_s3(bucket, key):
149
+ """
150
+ Cleans up the uploaded file from S3.
151
+ """
152
+ print(f"[*] Cleaning up temporary file from S3: {key}")
153
+ try:
154
+ s3_client = boto3.client(
155
+ 's3',
156
+ aws_access_key_id=AWS_ACCESS_KEY_ID,
157
+ aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
158
+ region_name=AWS_REGION
159
+ )
160
+ s3_client.delete_object(Bucket=bucket, Key=key)
161
+ print("[+] Temporary file deleted from S3 successfully.")
162
+ except Exception as e:
163
+ print(f"[!] Failed to delete temporary S3 object: {e}")
164
+
165
+ def generate_img2img(local_image_paths, prompt, output_path=None):
166
+ """
167
+ High-level API that does:
168
+ 1. S3 uploads
169
+ 2. Model task trigger
170
+ 3. Status polling
171
+ 4. Saving result locally
172
+ 5. Clean up S3 temporary files
173
+ """
174
+ if not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
175
+ raise ValueError("AWS_S3_ACCESS_KEY_ID or AWS_S3_SECRET_ACCESS_KEY is not configured in .env.")
176
+
177
+ # Validate that all input files exist
178
+ for img_path in local_image_paths:
179
+ if not os.path.exists(img_path):
180
+ raise FileNotFoundError(f"Local file '{img_path}' does not exist.")
181
+
182
+ s3_uploaded_keys = []
183
+ s3_urls = []
184
+ try:
185
+ # 1. Upload the local images to S3
186
+ for img_path in local_image_paths:
187
+ file_ext = os.path.splitext(img_path)[1] or ".png"
188
+ s3_temp_key = f"temp/{uuid.uuid4()}{file_ext}"
189
+ s3_url = upload_file_to_s3(img_path, AWS_BUCKET_NAME, s3_temp_key)
190
+ s3_uploaded_keys.append(s3_temp_key)
191
+ s3_urls.append(s3_url)
192
+
193
+ # 2. Invoke the image-to-image model
194
+ task_id = generate_image(s3_urls, prompt)
195
+
196
+ # 3. Poll for the task status with a 2-minute timeout
197
+ result_url = poll_task_status(task_id)
198
+
199
+ # 4. Save the result to the output path
200
+ if not output_path:
201
+ output_path = f"result_{int(time.time())}.png"
202
+ download_image(result_url, output_path)
203
+ return output_path
204
+
205
+ finally:
206
+ # 5. Clean up S3 temporary files
207
+ for key in s3_uploaded_keys:
208
+ delete_file_from_s3(AWS_BUCKET_NAME, key)
gpt_sim2real.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import argparse
3
+ import gpt_image
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser(description="Upload reference images to S3, call img2img model, poll for result, and cleanup temporary files.")
7
+ parser.add_argument("images", nargs="+", help="Paths to local reference images.")
8
+ parser.add_argument("-o", "--output", help="Output path for the generated image. Defaults to 'result_<timestamp>.png' in current directory.")
9
+ parser.add_argument("-p", "--prompt", default="生成ta的真人照片,再生成ta的背面放在图片右边", help="Prompt for the img2img model.")
10
+ args = parser.parse_args()
11
+
12
+ try:
13
+ gpt_image.generate_img2img(
14
+ local_image_paths=args.images,
15
+ prompt=args.prompt,
16
+ output_path=args.output
17
+ )
18
+ except Exception as e:
19
+ print(f"[!] Execution failed: {e}")
20
+ sys.exit(1)
21
+
22
+ if __name__ == '__main__':
23
+ main()
gpt_skin2real.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import uuid
4
+ import time
5
+ import argparse
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+ import mc_render
10
+ import gpt_image
11
+ from build_target_img import check_skin, ensure_valid_skin
12
+ from alice_to_steve import alice_to_steve
13
+ from mc_voxel_texture_resolver import resolve_voxel_consistency
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser(description="Render Minecraft skin to 3D views, upload to S3, and call img2img model.")
17
+ parser.add_argument("skin", help="Path to local Minecraft skin image file.")
18
+ parser.add_argument("-o", "--output", help="Output path for the generated image. Defaults to 'result_<timestamp>.png'.")
19
+ parser.add_argument("-p", "--prompt", default="生成ta的真人照片,再生成ta的背面放在图片右边", help="Prompt for the img2img model.")
20
+ parser.add_argument("-r", "--render-only", action="store_true", help="Only render the 3D front and back views locally, without calling the S3/img2img pipeline.")
21
+ args = parser.parse_args()
22
+
23
+ # 1. Validate skin path
24
+ if not os.path.exists(args.skin):
25
+ print(f"Error: Skin file '{args.skin}' does not exist.")
26
+ sys.exit(1)
27
+
28
+ # 2. Process/Validate the skin image (Alex/Steve conversion, validity, consistency)
29
+ try:
30
+ print(f"[*] Processing skin file: {args.skin}")
31
+ skin_image = Image.open(args.skin).convert('RGBA')
32
+ valid, is_alex = check_skin(skin_image)
33
+ if not valid:
34
+ print(f"Error: Skin '{args.skin}' fails validation.")
35
+ sys.exit(1)
36
+ if is_alex:
37
+ print("[*] Detected Alex skin. Converting to Steve...")
38
+ skin_image = alice_to_steve(skin_image)
39
+
40
+ skin_image = ensure_valid_skin(skin_image)
41
+ skin_image = resolve_voxel_consistency(skin_image)
42
+ except Exception as e:
43
+ print(f"[!] Skin processing failed: {e}")
44
+ sys.exit(1)
45
+
46
+ # 3. Generate front and back 3D renders using mc_render
47
+ pos_args2 = {
48
+ 'head': (0, 28, 0),
49
+ 'body': (0, 18, 0),
50
+ 'right_arm': (-6, 18, 0),
51
+ 'left_arm': (6, 18, 0),
52
+ 'right_leg': (-2, 6, 0),
53
+ 'left_leg': (2, 6, 0),
54
+ }
55
+
56
+ # Determine output filenames for renders
57
+ if args.render_only:
58
+ if args.output:
59
+ base, ext = os.path.splitext(args.output)
60
+ temp_front_path = f"{base}_front{ext or '.png'}"
61
+ temp_back_path = f"{base}_back{ext or '.png'}"
62
+ else:
63
+ temp_front_path = "render_front.png"
64
+ temp_back_path = "render_back.png"
65
+ else:
66
+ # Generate unique filenames for temp renders
67
+ unique_id = uuid.uuid4()
68
+ temp_front_path = f"temp_front_{unique_id}.png"
69
+ temp_back_path = f"temp_back_{unique_id}.png"
70
+
71
+ try:
72
+ print("[*] Rendering skin 3D front view...")
73
+ mc_render.render_skin(
74
+ skin=np.array(skin_image),
75
+ output_size=(768, 768),
76
+ cam_front=(0.25, 0.25, 0.25),
77
+ use_voxels=False,
78
+ ortho=False,
79
+ save_path=temp_front_path,
80
+ transparent_background=True,
81
+ zoom=0.3,
82
+ look_at_y=18,
83
+ pos_args=pos_args2,
84
+ off_screen=True
85
+ )
86
+
87
+ print("[*] Rendering skin 3D back view...")
88
+ mc_render.render_skin(
89
+ skin=np.array(skin_image),
90
+ output_size=(768, 768),
91
+ cam_front=(-0.25, 0.25, -0.25),
92
+ use_voxels=False,
93
+ ortho=False,
94
+ save_path=temp_back_path,
95
+ transparent_background=True,
96
+ zoom=0.3,
97
+ look_at_y=18,
98
+ pos_args=pos_args2,
99
+ off_screen=True
100
+ )
101
+
102
+ if args.render_only:
103
+ print(f"[+] Render-only mode active. Views saved to:\n - {temp_front_path}\n - {temp_back_path}")
104
+ return
105
+
106
+ # 4. Invoke gpt_image.generate_img2img
107
+ print("[*] Invoking image-to-image pipeline via gpt_image...")
108
+ output_file = gpt_image.generate_img2img(
109
+ local_image_paths=[temp_front_path, temp_back_path],
110
+ prompt=args.prompt,
111
+ output_path=args.output
112
+ )
113
+ print(f"[+] Pipeline completed successfully. Output saved to: {output_file}")
114
+
115
+ except Exception as e:
116
+ print(f"[!] Execution failed: {e}")
117
+ sys.exit(1)
118
+ finally:
119
+ # Clean up local temporary files if not in render-only mode
120
+ if not args.render_only:
121
+ for temp_file in [temp_front_path, temp_back_path]:
122
+ if os.path.exists(temp_file):
123
+ print(f"[*] Removing local temporary file: {temp_file}")
124
+ try:
125
+ os.remove(temp_file)
126
+ except Exception as e:
127
+ print(f"[!] Failed to remove local file {temp_file}: {e}")
128
+
129
+ if __name__ == '__main__':
130
+ main()