| import base64 |
| import os |
| import sys |
| import argparse |
| from pathlib import Path |
| import PIL.Image |
| from google import genai |
| from google.genai import types |
| from dotenv import load_dotenv |
|
|
| |
| env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '.env') |
| load_dotenv(env_path) |
|
|
| |
| DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'template', 'template5.png') |
|
|
|
|
| def _build_template_refs(count): |
| """Build the [图2][图3]...[图N+1] reference string for the prompt.""" |
| return "".join(f"[图{i}]" for i in range(2, count + 2)) |
|
|
|
|
| |
| |
| DEFAULT_PROMPT = """把[图1]中角色生成为参考图片的风格:{template_refs} |
| |
| 1. 请严格像素化(最高优先级),允许丢弃细节,texture不能高于Minecraft所支持的分辨率(64x64uvmap),参考{template_refs}。 |
| |
| 2. 生成角色的尺寸、朝向、姿势必须与{template_refs}完全一致,轮廓与内层或外层皮肤的每个像素完全贴合,不能用超出内外层皮肤的任何元素表达角色的特征,无光影特效。 |
| |
| 3. 使用容易区分前景的纯色背景。 |
| |
| 4. 准确的还原包括外貌特征、全身所有服装、各种饰品等(不包括手持物品和披风)""" |
|
|
|
|
| def real2render( |
| image_path, |
| template_paths=None, |
| output_path=None, |
| prompt=None, |
| aspect_ratio="1:1", |
| image_size="2K", |
| proxy=None, |
| ): |
| if not os.path.exists(image_path): |
| raise FileNotFoundError(f"Real character image '{image_path}' does not exist.") |
|
|
| if not template_paths: |
| template_paths = [DEFAULT_TEMPLATE_PATH] |
|
|
| for i, tp in enumerate(template_paths): |
| if not os.path.exists(tp): |
| raise FileNotFoundError(f"Template image {i + 2} '{tp}' does not exist.") |
|
|
| template_refs = _build_template_refs(len(template_paths)) |
| prompt_text = (prompt or DEFAULT_PROMPT).format(template_refs=template_refs) |
|
|
| print(f"[*] Real Image (Graph 1): {image_path}") |
| for i, tp in enumerate(template_paths): |
| print(f"[*] Template Image (Graph {i + 2}): {tp}") |
| print(f"[*] Image Size: {image_size}, Aspect Ratio: {aspect_ratio}") |
| print(f"[*] Prompt:\n{prompt_text}\n") |
|
|
| |
| images = [] |
| try: |
| images.append(PIL.Image.open(image_path)) |
| for tp in template_paths: |
| images.append(PIL.Image.open(tp)) |
| except Exception as e: |
| raise ValueError(f"Failed to load images with PIL: {e}") |
|
|
| |
| |
| contents = images + [prompt_text] |
|
|
| |
| import socket |
| proxy_url = proxy |
| if not proxy_url: |
| proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or os.environ.get("all_proxy") or os.environ.get("ALL_PROXY") |
|
|
| |
| if not proxy_url: |
| try: |
| with socket.create_connection(("127.0.0.1", 7897), timeout=0.2): |
| proxy_url = "http://127.0.0.1:7897" |
| print(f"[*] Auto-detected local Clash Verge proxy on {proxy_url}, using it.") |
| except Exception: |
| pass |
|
|
| client_args = {"http2": False} |
| if proxy_url: |
| client_args["proxy"] = proxy_url |
|
|
| client = genai.Client( |
| api_key=os.environ.get("GEMINI_API_KEY"), |
| http_options=types.HttpOptions( |
| client_args=client_args, |
| async_client_args=client_args |
| ) |
| ) |
|
|
| |
| config = types.GenerateContentConfig( |
| temperature=1, |
| max_output_tokens=32768, |
| top_p=0.95, |
| system_instruction='你是一个专业的minecraft皮肤绘手', |
| response_modalities=['image', 'text'], |
| image_config=types.ImageConfig( |
| aspect_ratio=aspect_ratio, |
| image_size=image_size |
| ) |
| ) |
|
|
| |
| max_retries = 5 |
| response = None |
| for attempt in range(1, max_retries + 1): |
| try: |
| response = client.models.generate_content( |
| model='models/gemini-3-pro-image', |
| contents=contents, |
| config=config |
| ) |
| break |
| except Exception as e: |
| if attempt == max_retries: |
| raise e |
| print(f"[!] Attempt {attempt} failed: {e}. Retrying in 2 seconds...") |
| import time |
| time.sleep(2) |
|
|
| |
| |
| image_data = None |
| for part in response.candidates[0].content.parts: |
| if part.inline_data: |
| if image_data is None: |
| image_data = part.inline_data.data |
| else: |
| if part.text: |
| print(f"[Info] Text response from Gemini: {part.text}") |
| else: |
| print(f"[Info] Non-image part: {part}") |
|
|
| if not image_data: |
| raise ValueError("No image was returned from Gemini API.") |
|
|
| import time |
| if not output_path: |
| output_path = f"official_api_test_{int(time.time())}.png" |
|
|
| |
| output_dir = os.path.dirname(output_path) |
| if output_dir and not os.path.exists(output_dir): |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| with open(output_path, "wb") as f: |
| f.write(image_data) |
|
|
| return output_path |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Convert real character photo to Minecraft render using Gemini Official API.") |
| parser.add_argument("image", help="Path to local real character photo (Graph 1).") |
| parser.add_argument( |
| "-t", "--template", |
| action="append", |
| default=None, |
| help="Path to a reference template image. May be specified multiple times " |
| "(e.g. -t t1.png -t t2.png -t t3.png). " |
| "Defaults to the built-in template if omitted." |
| ) |
| parser.add_argument("-o", "--output", help="Output path for the generated image.") |
| parser.add_argument("-p", "--prompt", default=None, |
| help="Path to a prompt text file. Use {template_refs} as placeholder for reference image tags in the file.") |
| parser.add_argument("-a", "--aspect-ratio", default="1:1", |
| choices=["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"], |
| help="Aspect ratio.") |
| parser.add_argument("-s", "--image-size", default="1K", choices=["1K", "2K", "4K"], help="Resolution size (default: 2K).") |
| parser.add_argument("-x", "--proxy", default=None, |
| help="Proxy URL (e.g., http://127.0.0.1:7897). If not provided, it will check environment variables and auto-detect Clash Verge.") |
| args = parser.parse_args() |
|
|
| try: |
| prompt_content = None |
| if args.prompt: |
| with open(args.prompt, "r", encoding="utf-8") as f: |
| prompt_content = f.read() |
|
|
| output_file = real2render( |
| image_path=args.image, |
| template_paths=args.template, |
| output_path=args.output, |
| prompt=prompt_content, |
| aspect_ratio=args.aspect_ratio, |
| image_size=args.image_size, |
| proxy=args.proxy |
| ) |
| print(f"[+] Task completed successfully. Output saved to: {output_file}") |
| except Exception as e: |
| print(f"[!] Execution failed: {e}") |
| sys.exit(1) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|
|
|