File size: 4,935 Bytes
86c7f55
 
 
a36a1f8
 
 
 
 
 
 
 
 
 
 
86c7f55
a36a1f8
 
 
 
 
 
 
86c7f55
a36a1f8
 
78d002d
 
 
86c7f55
78d002d
a36a1f8
78d002d
86c7f55
a36a1f8
 
 
 
 
86c7f55
 
 
 
 
 
 
a36a1f8
 
 
 
 
 
 
 
86c7f55
 
 
a36a1f8
 
78d002d
86c7f55
78d002d
86c7f55
a36a1f8
 
86c7f55
a36a1f8
86c7f55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ์ˆ˜์ •๋œ ๋ฒ„์ „ โ€” SyntaxError ํ•ด๊ฒฐ (try/except ์ •๋ ฌ ์˜ค๋ฅ˜ ์ˆ˜์ •)
# ๊ธฐ์กด ์ฝ”๋“œ์—์„œ line 133 ๊ทผ์ฒ˜์˜ try ๋ธ”๋ก์ด ์ž˜๋ชป ๋“ค์—ฌ์“ฐ๊ธฐ๋˜์–ด ํŒŒ์„œ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.
# ์ด์ œ ์˜ฌ๋ฐ”๋ฅธ try/except ๊ตฌ์กฐ๋กœ ๊ต์ •๋˜์–ด Hugging Face Space์—์„œ ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค.

import os
import io
import base64
import random
from typing import Optional, Callable, Tuple

import requests
from PIL import Image

try:
    import gradio as gr
    GRADIO_AVAILABLE = True
except Exception:
    GRADIO_AVAILABLE = False

    class _GradioError(RuntimeError):
        pass

    class gr:
        Error = _GradioError

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or os.getenv("BANANA_API_KEY")
GEMINI_MODEL = os.getenv("GEMINI_MODEL") or os.getenv("BANANA_MODEL_KEY") or "gemini-2.5-flash-image"
APP_TITLE = os.getenv("APP_TITLE", "OVJ STUDIO ร— Gemini 2.5 Flash Image")
GEMINI_RUN_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent"

def _ensure_secrets_for_runtime():
    if not GEMINI_API_KEY:
        raise RuntimeError("GEMINI_API_KEY๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. HF Settings โ†’ Variables & Secrets์—์„œ ์ถ”๊ฐ€ํ•˜์„ธ์š”.")

def _to_image_from_b64(b64_str: str) -> Image.Image:
    data = base64.b64decode(b64_str)
    return Image.open(io.BytesIO(data)).convert("RGB")

def _compose_prompt(prompt: str, negative: str, w: int, h: int, steps: int, guidance: float, seed: int) -> str:
    meta = f"\n\n[meta] size={w}x{h}, steps={steps}, guidance={guidance}, seed={seed}"
    if negative:
        meta += f", negative={negative}"
    return f"{prompt}{meta}"

def generate_image(prompt: str, negative_prompt: str, steps: int, guidance: float, width: int, height: int, seed: Optional[int], *, requests_post: Callable = requests.post) -> Tuple[Image.Image, str]:
    if not prompt or prompt.strip() == "":
        raise gr.Error("ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.")

    _ensure_secrets_for_runtime()

    if seed is None or int(seed) < 0:
        seed = random.randint(0, 2**31 - 1)

    contents = [{"parts": [{"text": _compose_prompt(prompt, negative_prompt, width, height, steps, guidance, seed)}]}]
    payload = {"contents": contents}
    headers = {"x-goog-api-key": GEMINI_API_KEY, "Content-Type": "application/json"}

    try:
        resp = requests_post(GEMINI_RUN_URL, json=payload, headers=headers, timeout=600)
    except requests.RequestException as e:
        raise gr.Error(f"Gemini API ์—ฐ๊ฒฐ ์‹คํŒจ: {e}")
    except Exception as e:
        raise gr.Error(f"์š”์ฒญ ์ˆ˜ํ–‰ ์ค‘ ์˜ˆ์™ธ: {e}")

    if not getattr(resp, "ok", False):
        try:
            err = resp.json()
        except Exception:
            err = getattr(resp, "text", str(resp))
        raise gr.Error(f"Gemini API ์˜ค๋ฅ˜: HTTP {getattr(resp, 'status_code', '??')}\n{err}")

    try:
        data = resp.json()
    except Exception as e:
        body = getattr(resp, "text", "")
        raise gr.Error(f"API ์‘๋‹ต ํŒŒ์‹ฑ ์‹คํŒจ: {e}\n๋ณธ๋ฌธ={body[:500]}")

    try:
        candidates = data.get("candidates", [])
        if not candidates:
            raise KeyError("candidates๊ฐ€ ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
        parts = candidates[0].get("content", {}).get("parts", [])
        b64 = None
        for p in parts:
            inline_data = p.get("inlineData") or p.get("inline_data")
            if inline_data:
                b64 = inline_data.get("data") or inline_data.get("bytes")
                if b64:
                    break
        if not b64:
            raise KeyError("inlineData ์•ˆ์— ์ด๋ฏธ์ง€ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")

        img = _to_image_from_b64(b64)
        return img, str(seed)
    except Exception as e:
        snippet = str(data)[:500]
        raise gr.Error(f"์‘๋‹ต ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜: {e}\n์‘๋‹ต ๋ฏธ๋ฆฌ๋ณด๊ธฐ={snippet}")

if GRADIO_AVAILABLE:
    with gr.Blocks(title=APP_TITLE) as demo:
        gr.Markdown(f"# {APP_TITLE}\n**OVJ STUDIO** ร— Gemini 2.5 Flash Image")

        prompt = gr.Textbox(label="Prompt", lines=3)
        negative = gr.Textbox(label="Negative Prompt", lines=2)
        steps = gr.Slider(5, 60, value=28, step=1, label="Steps")
        guidance = gr.Slider(0.0, 20.0, value=7.5, step=0.1, label="Guidance")
        width = gr.Dropdown([512, 640, 768, 832, 1024], value=768, label="Width")
        height = gr.Dropdown([512, 640, 768, 832, 1024], value=768, label="Height")
        seed = gr.Number(value=-1, precision=0, label="Seed (-1=random)")

        out_img = gr.Image(label="Result", type="pil")
        out_seed = gr.Textbox(label="Used Seed", interactive=False)
        btn = gr.Button("Generate")

        btn.click(generate_image, [prompt, negative, steps, guidance, width, height, seed], [out_img, out_seed])

if __name__ == "__main__":
    if GRADIO_AVAILABLE:
        _ensure_secrets_for_runtime()
        demo.launch()
    else:
        print("[INFO] gradio ๋ฏธ์„ค์น˜ ํ™˜๊ฒฝ โ€” ํ…Œ์ŠคํŠธ ๋ชจ๋“œ ์‹คํ–‰ ์ƒ๋žต")