File size: 4,811 Bytes
c1d1da2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""
Google AI Studio Image Generation Script for Generals & TCG Cards
Uses Google AI Studio API (gemini-3.1-flash-image / gemini-3-pro-image)
Automatically saves master JPG and runs high-precision cutout (isnet-general-use)
"""

import os
import sys
import json
import base64
import argparse
import requests
from PIL import Image

def get_api_key():
    key = os.environ.get('GEMINI_API_KEY')
    if key:
        return key
    env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
    if os.path.exists(env_path):
        with open(env_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line.startswith('GEMINI_API_KEY='):
                    return line.split('=', 1)[1].strip()
    return None

def generate_image(prompt, output_jpg, model='gemini-3.1-flash-image'):
    key = get_api_key()
    if not key:
        print("[ERROR] GEMINI_API_KEY not found in environment or .env file.")
        return False

    url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}"
    payload = {
        "contents": [{
            "parts": [{"text": prompt}]
        }],
        "generationConfig": {
            "responseModalities": ["IMAGE"]
        }
    }

    print(f"[*] Calling Google AI Studio ({model})...")
    res = requests.post(url, json=payload, timeout=60)
    
    if res.status_code != 200:
        print(f"[!] API Error ({res.status_code}):")
        try:
            err = res.json().get('error', {})
            print(f"    Message: {err.get('message')}")
            print(f"    Status: {err.get('status')}")
            if "limit: 0" in err.get('message', ''):
                print("\n[!] 提示:您的 Google AI Studio 專案目前屬於【Free Tier】方案。")
                print("    Google 規範中,生圖模型(gemini-*-image)在免費方案中的配額為 0(limit: 0)。")
                print("    請至 https://aistudio.google.com/ 點擊【Set up billing】綁定信用卡開啟隨用隨付(Pay-as-you-go)。")
                print("    開通後單張生圖成本約僅需 $0.03 美元(約新台幣 1 元),即可立即解除配額限制!")
        except:
            print(res.text)
        return False

    data = res.json()
    candidates = data.get('candidates', [])
    if not candidates:
        print("[!] No candidates returned in response.")
        return False

    parts = candidates[0].get('content', {}).get('parts', [])
    image_bytes = None
    for p in parts:
        if 'inlineData' in p and p['inlineData'].get('data'):
            image_bytes = base64.b64decode(p['inlineData']['data'])
            break

    if not image_bytes:
        print("[!] No inline image data found in candidate parts.")
        return False

    os.makedirs(os.path.dirname(os.path.abspath(output_jpg)), exist_ok=True)
    with open(output_jpg, 'wb') as f:
        f.write(image_bytes)
    
    img = Image.open(output_jpg)
    print(f"[+] Master image saved to: {output_jpg} (Size: {img.size})")
    return True

def cutout_image(src_jpg, dest_png):
    from rembg import remove, new_session
    import numpy as np

    print(f"[*] Running high-precision cutout (isnet-general-use) on: {src_jpg}...")
    input_img = Image.open(src_jpg)
    session = new_session('isnet-general-use')
    output_img = remove(input_img, session=session)
    output_img.save(dest_png, format='PNG')
    
    arr = np.array(output_img)
    alpha = arr[:, :, 3]
    nonzero = np.argwhere(alpha > 10)
    if len(nonzero) > 0:
        ymin, xmin = nonzero.min(axis=0)
        ymax, xmax = nonzero.max(axis=0)
        print(f"[+] Transparent cutout saved to: {dest_png}")
        print(f"    Bounding Box: y=[{ymin}, {ymax}], x=[{xmin}, {xmax}] (Height: {ymax - ymin}px)")
    else:
        print(f"[+] Saved to: {dest_png}")
    return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Generate image via Google AI Studio")
    parser.add_argument("--prompt", required=True, help="Prompt text or path to prompt text file")
    parser.add_argument("--output", required=True, help="Path for output JPG")
    parser.add_argument("--cutout", action="store_true", help="Automatically generate transparent PNG with rembg")
    parser.add_argument("--model", default="gemini-3.1-flash-image", help="Model name")

    args = parser.parse_args()

    prompt_text = args.prompt
    if os.path.exists(args.prompt):
        with open(args.prompt, 'r', encoding='utf-8') as f:
            prompt_text = f.read()

    success = generate_image(prompt_text, args.output, model=args.model)
    if success and args.cutout:
        png_path = os.path.splitext(args.output)[0] + '.png'
        cutout_image(args.output, png_path)