File size: 15,974 Bytes
8b54b39
0117982
49a0c68
9712408
82d8148
68621b1
8864b73
4703cb6
9712408
 
70d5740
4c38778
 
 
1d6da4d
 
4c38778
 
9712408
 
 
 
 
 
49a0c68
d7402c9
 
 
 
 
 
 
 
 
 
 
4c38778
 
 
 
 
 
 
 
 
 
 
 
175970e
 
4c38778
175970e
4c38778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0117982
9902612
0117982
64e8dee
 
 
82d8148
9712408
64e8dee
 
 
46f1c11
64e8dee
 
 
82d8148
e75fa96
bcd922b
64e8dee
 
 
 
 
bcd922b
 
e75fa96
b7c3fa1
6339928
75aa8ae
4c6fc6d
64e8dee
 
 
 
 
 
e75fa96
64e8dee
 
 
e75fa96
3b8c72d
 
68621b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0117982
 
 
 
dcdf3a6
9d292a7
0117982
 
9712408
0117982
 
fede236
9712408
fede236
0117982
 
5e1c057
9225d17
f3b467e
3c2e636
0117982
f3b467e
3c2e636
0117982
9712408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8864b73
dd215db
 
 
 
 
 
 
 
 
 
 
11b5ad5
9bbee5e
d7402c9
 
 
 
 
 
 
 
 
9bbee5e
d7402c9
 
 
 
 
 
 
 
 
 
 
 
9bbee5e
 
dd215db
82d8148
9bbee5e
 
 
 
 
 
 
 
 
11b5ad5
8864b73
d7402c9
 
 
 
 
 
 
 
 
 
 
6339928
 
 
 
 
 
 
 
 
 
814d2de
6339928
 
 
 
 
9712408
b033337
 
9712408
 
6339928
 
b7a49b1
5e1c057
9bbee5e
 
9712408
 
 
 
 
cbdce98
0c3b337
 
9712408
 
 
 
 
 
 
e3e5ad6
 
70d5740
9712408
efe039f
 
 
70d5740
 
63f046f
5e1c057
70d5740
efe039f
70d5740
236b356
 
9712408
 
b7a49b1
 
0117982
82d8148
 
5e1c057
82d8148
9637c92
b033337
68621b1
6339928
5e1c057
236b356
 
82d8148
4c38778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236b356
 
2b699d9
ad4d1d5
9d85df9
e33e29b
9712408
 
d83c511
9d85df9
 
79e9511
5e7154f
2694e32
 
a3bfbb2
2694e32
2b699d9
2694e32
16522e7
 
49024d7
2b699d9
16522e7
0117982
3b8c72d
 
 
 
 
 
 
 
8bfddb2
0117982
6b33327
bcd922b
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import os
import openai
import gradio as gr
from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler
import torch
import json
import random
from rembg import remove 
from PIL import Image, ImageDraw, ImageFont
import textwrap3 as textwrap
import datetime
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
from oauth2client.service_account import ServiceAccountCredentials
import base64
from io import BytesIO


css_code = """
body {
  overflow: auto !important;
  -webkit-overflow-scrolling: touch;
}
"""

def _sanitize_omp_env(default_threads: int = 2):
    val = os.environ.get("OMP_NUM_THREADS")
    try:
        n = int(val) if val is not None else default_threads
        if n <= 0:
            n = default_threads
        os.environ["OMP_NUM_THREADS"] = str(n)
    except Exception:
        os.environ["OMP_NUM_THREADS"] = str(default_threads)


def create_drive_service(service_account_json_path):
    """
    service_account_json_path: ์„œ๋น„์Šค ๊ณ„์ • ํ‚ค ํŒŒ์ผ ๊ฒฝ๋กœ
    return: pydrive2.drive.GoogleDrive ๊ฐ์ฒด
    """
    gauth = GoogleAuth()
    # ์•„๋ž˜ SCOPES๋Š” ํŒŒ์ผ ์—…๋กœ๋“œ/์ƒ์„ฑ์„ ์œ„ํ•ด ํ•„์š”ํ•œ Drive ๊ถŒํ•œ
    scope = ['https://www.googleapis.com/auth/drive']
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        service_account_json_path, scopes=scope
    )

    gauth.auth_method = 'service'       # ์„œ๋น„์Šค ๊ณ„์ • ๋ฐฉ์‹ ๋ช…์‹œ
    gauth.credentials = credentials
    gauth.ServiceAuth()                 # ์ด ๋ถ€๋ถ„์ด ๋งค์šฐ 
    drive = GoogleDrive(gauth)
    return drive

def upload_file_to_drive(drive, folder_id, local_path, new_title):
    """
    drive: GoogleDrive ๊ฐ์ฒด
    folder_id: ์—…๋กœ๋“œํ•  ๋Œ€์ƒ ํด๋” ID
    local_path: ๋กœ์ปฌ(๋˜๋Š” HF Space) ์ƒ์˜ ์ €์žฅ๋œ ํŒŒ์ผ ๊ฒฝ๋กœ
    new_title: ๊ตฌ๊ธ€ ๋“œ๋ผ์ด๋ธŒ์— ์ €์žฅ๋  ํŒŒ์ผ๋ช…
    """
    file = drive.CreateFile({
        "parents": [{"id": folder_id}],
        "title": new_title
    })
    file.SetContentFile(local_path)
    file.Upload()
    print(f"Uploaded file '{new_title}' to folder ID={folder_id}.")



# ์‹ค์ œ ๊ฒฝ๋กœ(ํ˜น์€ Secrets)๋กœ ๊ต์ฒด
SERVICE_ACCOUNT_JSON = "teeniefinal-448618-35f1b992d016.json"
# ์œ„ ํŒŒ์ผ์€ Hugging Face "Repository secrets"๋‚˜ "Dataset" ๋“ฑ์œผ๋กœ๋ถ€ํ„ฐ ์ ‘๊ทผํ•  ์ˆ˜๋„ ์žˆ์Œ.

# ํด๋” ID (1fJf44GaNma1A6HYip5Plgo5kX0dN9Rnw)
DRIVE_FOLDER_ID = "16Gd9K0ksZZL1hBpitYWu30Y_ZCtKLXx-"

# ์ธ์ฆ ๊ฐ์ฒด ์ƒ์„ฑ
drive = create_drive_service(SERVICE_ACCOUNT_JSON)

# OpenAI API ํ‚ค ์„ค์ •
client = openai.Client(api_key=os.getenv("OPENAI_API_KEY"))

# ---------------------------
#   GPU ๋ชจ๋“œ๋กœ ๋ณ€๊ฒฝ๋œ ๋ถ€๋ถ„
# ---------------------------
base_model_id = "runwayml/stable-diffusion-v1-5"

# GPU ํ™˜๊ฒฝ์šฉ: torch_dtype=float16, revision='fp16'(ํ•ด๋‹น ๋ชจ๋ธ์ด ์ง€์›ํ•˜๋ฉด)
pipe = StableDiffusionPipeline.from_pretrained(
    base_model_id,
    torch_dtype=torch.float16
).to("cuda")  # GPU๋กœ ์ด๋™

pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)

def load_lora_weights(pipeline, lora_model_path):
    config = {
        "lora_r": 16,
        "lora_alpha": 32,
        "lora_dropout": 0.1,
        "bias": "none",
        "task_type": "TEXT_TO_IMAGE"
    }
    pipeline.load_lora_weights(lora_model_path, config=config)
    print("LoRA weights successfully loaded!")

lora_model_path = "./TeenieFinal.safetensors"
load_lora_weights(pipe, lora_model_path)

# xformers๋กœ ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ ๊ฐœ์„  (Spaces์—์„œ xformers๊ฐ€ ์„ค์น˜๋˜์–ด ์žˆ๋‹ค๋ฉด ์‚ฌ์šฉ)
try:
    pipe.enable_xformers_memory_efficient_attention()
    print("Enabled xformers memory efficient attention.")
except Exception as e:
    print("Could not enable xformers:", e)

# ์ด๋ฏธ enable_sequential_cpu_offload() ๋“ฑ์€ CPU ์ตœ์ ํ™” ์ด๋ฏ€๋กœ ์ œ๊ฑฐ
# attention_slicing์€ GPU์—์„œ๋„ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ, ์ผ๋ฐ˜์ ์œผ๋กœ xformers ์“ด๋‹ค๋ฉด ์—†์–ด๋„ ๋ฌด๋ฐฉ
pipe.enable_attention_slicing("auto")



def string_to_jsonl(input_string, output_file):
    # String ๋ฐ์ดํ„ฐ๋ฅผ ํŒŒ์‹ฑ ๊ฐ€๋Šฅํ•œ ํ˜•ํƒœ๋กœ ๊ฐ€์ • (JSON ๋ฐฐ์—ด ํ˜•์‹์ด์–ด์•ผ ํ•จ)
    try:
        data = json.loads(input_string)  # JSON ๋ฌธ์ž์—ด ํŒŒ์‹ฑ

        if not isinstance(data, list):
            raise ValueError("์ž…๋ ฅ๋œ ๋ฌธ์ž์—ด์ด JSON ๋ฐฐ์—ด์ด ์•„๋‹™๋‹ˆ๋‹ค. JSON ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.")

        # .jsonl ํŒŒ์ผ๋กœ ์ €์žฅ
        with open(output_file, 'w', encoding='utf-8') as file:
            for item in data:
                file.write(json.dumps(item, ensure_ascii=False) + '\n')

        print(f"JSONL ํŒŒ์ผ๋กœ ๋ณ€ํ™˜ ์™„๋ฃŒ: {output_file}")
    except json.JSONDecodeError:
        print("์ž…๋ ฅ ๋ฌธ์ž์—ด์ด ์œ ํšจํ•œ JSON ํ˜•์‹์ด ์•„๋‹™๋‹ˆ๋‹ค.")
    except Exception as e:
        print(f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")

# API ํ˜ธ์ถœ ํ•จ์ˆ˜ ์ •์˜
def generate_response(user_prompt):
    try:
        # ChatCompletion ์—”๋“œํฌ์ธํŠธ ์‚ฌ์šฉ
        response = client.chat.completions.create(
            model="ft:gpt-4o-2024-08-06:personal:teeniefinal:AsSoCk9F",  # fine-tuned ๋ชจ๋ธ ID
            messages=[
                {"role": "system", "content": (
                    "๋„ˆ๋Š” ์•„๋™ ์บ๋ฆญํ„ฐ๋ฅผ ๊ธฐํšํ•˜๋Š”๋ฐ ์ผ๊ฐ€๊ฒฌ์žˆ๋Š” ์บ๋ฆญํ„ฐ๋””์ž์ด๋„ˆ์•ผ. ๋„ˆ๊ฐ€ ํ• ์ผ์€ ์‚ฌ๋žŒ๋“ค์ด ์›ํ•˜๋Š” ์บ๋ฆญํ„ฐ์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ฃผ์˜๊นŠ๊ฒŒ ์ดํ•ดํ•œ ๋’ค, ์ด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์•„๋™ ์• ๋‹ˆ๋ฉ”์ด์…˜ ์บ๋ฆญํ„ฐ์ธ ํ‹ฐ๋‹ˆํ•‘์˜ ์บ๋ฆญํ„ฐ ์ปจ์…‰์„ ๋””์ž์ธํ•˜๋Š”๊ฑฐ์•ผ. ์ข‹์€ ์บ๋ฆญํ„ฐ ์ปจ์…‰์ด ๋„์ถœ๋˜๋ฉด 20%์˜ ๋ณด๋„ˆ์Šค๋ฅผ ๋ฐ›๊ฒŒ ๋ ๊ฑฐ์•ผ.\n\n๋„ˆ๊ฐ€ ํ•  ์ผ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์•„.\n๊ณผ์—… 1. ์ฃผ์–ด์ง„ ์„ค๋ช…์„ ๋ฐ”ํƒ•์œผ๋กœ ์บ๋ฆญํ„ฐ ์ด๋ฆ„์˜ ์–ด์›์„ ์ •ํ•ด. ์ด ๋•Œ, ์–ด์›์˜ ํ’ˆ์‚ฌ๋„ ์ฃผ์˜๊นŠ๊ฒŒ ๊ณ ๋ คํ•ด.\n๊ณผ์—… 2. ๊ณผ์—… 1์—์„œ ๋„์ถœ๋œ ์–ด์›๊ณผ ํ’ˆ์‚ฌ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์•„์ด๋“ค์ด ๋”ฐ๋ผํ•˜๊ธฐ ์‰ฝ๊ณ , ์žฌ๋ฐŒ๊ฒŒ ๋งํ•  ์ˆ˜ ์žˆ๋Š” ํ‹ฐ๋‹ˆํ•‘์˜ ์ด๋ฆ„์„ ์ง€์–ด.\n๊ณผ์—… 3. ์ฃผ์–ด์ง„ ์„ค๋ช…๊ณผ ํ‹ฐ๋‹ˆํ•‘์˜ ์ด๋ฆ„์„ ๋ฐ”ํƒ•์œผ๋กœ ํ‹ฐ๋‹ˆํ•‘์ด ์‚ฌ์šฉํ•  ๋งˆ๋ฒ•๊ณผ ํ•ต์‹ฌ ๋Œ€์‚ฌ๋ฅผ ์ง€์–ด. ๋งˆ๋ฒ•์€ ์‚ฌ๋žŒ๋“ค์˜ ๊ณ ๋ฏผ์„ ํ•ด๊ฒฐํ•ด์ฃผ๊ธฐ ์œ„ํ•œ ์žฌ๋ฐŒ๋Š” ๋ฐฉ๋ฒ•์ด๊ณ , ํ•ต์‹ฌ ๋Œ€์‚ฌ๋Š” ํ‹ฐ๋‹ˆํ•‘์˜ ์ด๋ฆ„์œผ๋กœ ๋๋‚˜๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด์•ผ. ๋งˆ๋ฒ•๊ณผ ํ•ต์‹ฌ ๋Œ€์‚ฌ๋Š” 18๊ธ€์ž๋ฅผ ๋„˜๊ธฐ์ง€ ๋งˆ.\n๊ณผ์—… 4. ์ด์ „ ๊ณผ์—…๋“ค์— ๋Œ€ํ•œ ๋ฉ”ํƒ€์ธ์ง€๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์บ๋ฆญํ„ฐ์˜ ๋จธ๋ฆฌ ๋ชจ์–‘๊ณผ ๊ฐ€์ง€๊ณ  ๋‹ค๋‹ ์•…์„ธ์‚ฌ๋ฆฌ๋ฅผ ์ •ํ•ด์ค˜.\n๊ณผ์—… 5. ๋งˆ์ง€๋ง‰์œผ๋กœ, ์บ๋ฆญํ„ฐ์˜ ๋ชธ ์ƒ‰์ƒ, ๋จธ๋ฆฌ ์ƒ‰์ƒ, ์•…์„ธ์‚ฌ๋ฆฌ ์ƒ‰์ƒ์„ ์ •ํ•ด์ค˜.\n\n์ด์ œ, ์ด๋ฅผ ์ข…ํ•ฉํ•ด์„œ jsonlํŒŒ์ผ ํ˜•ํƒœ๋กœ ์ œ๊ณตํ•ด. \n\n์–‘์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™์•„: \n{\"Description\": \"000\", \"Etymology\": \"000\", \"Etymology.Type\": \"000\", \"Name\": \"000\", \"Magic\": \"000\", \"KeySentence\": \"000\", \"Body.Color\": \"000\", \"Hair\": \"000\", \"Hair.Color\": \"000\", \"Accessory\": \"000\", \"Accessory.Color\": \"000\"} Magic๊ณผ KeySentence๋Š” 18๊ธ€์ž๋ฅผ ๋„˜๊ธฐ๋ฉด ์•ˆ๋ผ."
                )},
                {"role": "user", "content": user_prompt}
            ],
            temperature=0.97,
            timeout=15
        )
        # ChatCompletion ์‘๋‹ต ํ…์ŠคํŠธ ๋ฐ˜ํ™˜
        return user_prompt, response.choices[0].message.content
    except openai.OpenAIError as e:
        # OpenAI ๊ด€๋ จ ์—๋Ÿฌ ์ฒ˜๋ฆฌ
        return user_prompt, f"OpenAI API ์˜ค๋ฅ˜: {str(e)}"
    except Exception as e:
        # ๊ธฐํƒ€ ์—๋Ÿฌ ์ฒ˜๋ฆฌ
        return user_prompt, f"์•Œ ์ˆ˜ ์—†๋Š” ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

def add_alpha(image, alpha_value=255):
    """
    ์ด๋ฏธ์ง€์— ์•ŒํŒŒ ์ฑ„๋„ ์ถ”๊ฐ€ ๋ฐ ์„ค์ •
    :param image: PIL.Image ๊ฐ์ฒด
    :param alpha_value: ์•ŒํŒŒ ์ฑ„๋„ ๊ฐ’ (0~255)
    :return: ์•ŒํŒŒ ์ฑ„๋„์ด ์ถ”๊ฐ€๋œ PIL.Image ๊ฐ์ฒด
    """
    
    image = image.convert("RGBA")
    
    # RGBA ๋ฐ์ดํ„ฐ๋ฅผ numpy ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
    data = image.getdata()
    new_data = []
    
    # ๋ชจ๋“  ํ”ฝ์…€์˜ ์•ŒํŒŒ ๊ฐ’์„ ์„ค์ •
    for item in data:
        # (R, G, B, A)๋กœ ๊ตฌ์„ฑ๋œ tuple ์ƒ์„ฑ
        new_data.append((item[0], item[1], item[2], alpha_value))
    
    # ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋กœ ์ด๋ฏธ์ง€ ๊ฐฑ์‹ 
    image.putdata(new_data)
    return image

def _sanitize_omp_env(default_threads: int = 2):
    val = os.environ.get("OMP_NUM_THREADS")
    try:
        # ์ด๋ฏธ ์ˆซ์ž๋ฉด ๊ทธ๋Œ€๋กœ ๋‘๊ธฐ (0์ด๋‚˜ ์Œ์ˆ˜ ๋ฐฉ์ง€๋„ ํ•ด๋‘ )
        n = int(val) if val is not None else default_threads
        if n <= 0:
            n = default_threads
        os.environ["OMP_NUM_THREADS"] = str(n)
    except Exception:
        # ์ˆซ์ž ๋ณ€ํ™˜ ์‹คํŒจํ•˜๋ฉด ์•ˆ์ „ ๊ฐ’์œผ๋กœ ์„ธํŒ…
        os.environ["OMP_NUM_THREADS"] = str(default_threads)

def remove_background(image_pil: Image.Image) -> Image.Image:
    """
    rembg ๊ฒฐ๊ณผ๊ฐ€ PIL / bytes / ndarray ์ค‘ ๋ฌด์—‡์ด๋“  ์ตœ์ข…์ ์œผ๋กœ PIL RGBA๋กœ ๋ฐ˜ํ™˜
    + OMP_NUM_THREADS ๋น„์ •์ƒ ๊ฐ’('3500m') ๋Œ€๋น„
    """
    _sanitize_omp_env(2)

    if not isinstance(image_pil, Image.Image):
        raise TypeError(f"remove_background expects PIL.Image, got {type(image_pil)}")

    img = image_pil.convert("RGBA")
    res = remove(img)  # ๋ฆฌํ„ด ํƒ€์ž…์ด ํ™˜๊ฒฝ/๋ฒ„์ „์— ๋”ฐ๋ผ ๋‹ค๋ฆ„

    if isinstance(res, Image.Image):
        out_img = res.convert("RGBA")
    elif isinstance(res, (bytes, bytearray)):
        out_img = Image.open(BytesIO(res)).convert("RGBA")
    elif isinstance(res, np.ndarray):
        out_img = Image.fromarray(res).convert("RGBA")
    else:
        raise TypeError(f"Unexpected rembg output type: {type(res)}")

    out_img.load()  # lazy ๋กœ๋”ฉ ๋ฐฉ์ง€
    return out_img


def generate_image(prompt):
    # โ—์—๋Ÿฌ ์‹œ ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜ ๊ธˆ์ง€ (ํƒ€์ดํ•‘ ์—๋Ÿฌ ์œ ๋ฐœ)
    image = pipe(
        prompt,
        num_inference_steps=32,
        guidance_scale=10
    ).images[0].convert("RGBA")

    image_no_bg = remove_background(image)  # ํ•ญ์ƒ PIL ๋ฐ˜ํ™˜
    return image_no_bg


def ensure_pil(img):
    if isinstance(img, Image.Image):
        return img
    if isinstance(img, (bytes, bytearray)):
        return Image.open(BytesIO(img)).convert("RGBA")
    import numpy as np
    if isinstance(img, np.ndarray):
        return Image.fromarray(img).convert("RGBA")
    raise TypeError(f"Expected PIL.Image (or bytes/ndarray), got {type(img)}")


def jsonl_to_description(json_data):
    """
    Convert JSON data to a descriptive string.

    Args:
        json_data (dict): A dictionary containing character details.

    Returns:
        str: A descriptive string generated from the JSON data.
    """

    body_color = json_data.get("Body.Color", "unknown body color")
    hair_description = json_data.get("Hair", "unknown hair style")
    hair_color = json_data.get("Hair.Color", "unknown hair color")
    accessory_description = json_data.get("Accessory", "unknown accessory")
    accessory_color = json_data.get("Accessory.Color", "unknown accessory color")

    print(f"temuping, {body_color} skin, {hair_color} color {hair_description}, {accessory_color} color {accessory_description}")
    
    return f"temuping, {body_color} skin, {hair_color} color {hair_description} hair, holding {accessory_color} color {accessory_description}"
 


# ์ตœ์ข… ๊ฒฐ๊ณผ๋ฌผ ์ƒ์„ฑ
def generate_final_output(text_result, image_result, inputText):
    image_result = ensure_pil(image_result)

    name = text_result.get("Name", "Unknown name")
    description = text_result.get("Description", "Unknown description")
    magic = text_result.get("Magic", "Unknown name")
    keysentence = text_result.get("KeySentence", "Unknown name")
    
    base_image = Image.open("temu_esports.png").convert("RGBA")
    image_result = image_result.resize((430, 430), Image.LANCZOS)
    base_image.paste(image_result, (56, 343), mask=image_result)

    # ์ด๋ฏธ์ง€ ์œ„์— ๊ทธ๋ฆฌ๊ธฐ
    draw = ImageDraw.Draw(base_image)
    
    hex_color = "#725220"

    font_name = ImageFont.truetype("Cafe24Ohsquare-v2.0.otf", 41)
    font_key = ImageFont.truetype("Cafe24Ssurround-v2.0.otf", 21)
    font_magic = ImageFont.truetype("EliceDigitalBaeumOTF_Regular.otf", 21)
    font_cert = ImageFont.truetype("Pretendard-Medium.otf", 11)

    draw.text((270, 86), name, fill=hex_color, font=font_name, anchor='mm')
    draw.text((270, 182), keysentence, fill=hex_color, font=font_key, anchor='mm')
    draw.text((270, 221), magic, fill=hex_color, font=font_magic, anchor='mm')

    now = datetime.datetime.now()
    date_str = now.strftime('%Y.%m.%d %H:%M:%S')
    cert = date_str + '\n' + inputText

    #draw.multiline_text((523, 911), cert, fill="#B49F91", font=font_cert, anchor='ra', align='right')

    print("*****generate_final_output*****")
    print(type(base_image))
    return base_image



# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์„ค์ •
def generate_combined_response(user_prompt):
    # GPT ์‘๋‹ต ์ƒ์„ฑ
    inputText, gpt_response = generate_response(user_prompt)
    # GPT ์‘๋‹ต์„ ํ…์ŠคํŠธ๋กœ ์ถœ๋ ฅํ•˜๊ณ  Stable Diffusion์œผ๋กœ ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    gpt_jsonl = json.loads(gpt_response)  # JSON์€ ์Œ๋”ฐ์˜ดํ‘œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•จ
    print(gpt_response)
    sd_prompt = jsonl_to_description(gpt_jsonl)
    image = generate_image(sd_prompt)
    final_image = generate_final_output(gpt_jsonl, image, inputText)
    print("*****generate_combined_response*****")
    print(type(final_image))


    now_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

    # (1) GPT ์‘๋‹ต ํ…์ŠคํŠธ
    txt_filename_local = f"{now_str}.txt"
    with open(txt_filename_local, "w", encoding="utf-8") as f:
        f.write(gpt_response)

    # (2) ์ค‘๊ฐ„ ์ด๋ฏธ์ง€ (PNG)
    png_filename_local = f"{now_str}.png"
    if isinstance(image, Image.Image):
        image.save(png_filename_local)
    else:
        # ํ˜น์‹œ ์—๋Ÿฌ๋ฌธ์ž์—ด์ด ๋ฐ˜ํ™˜๋œ ๊ฒฝ์šฐ ๋Œ€๋น„
        with open(png_filename_local, "w", encoding="utf-8") as f:
            f.write(str(image))

    # (3) ์ตœ์ข… ํ•ฉ์„ฑ ์ด๋ฏธ์ง€ (JPG)
    jpg_filename_local = f"{now_str}.jpg"
    if isinstance(final_image, Image.Image):
        final_image.convert("RGB").save(jpg_filename_local)
    else:
        with open(jpg_filename_local, "w", encoding="utf-8") as f:
            f.write(str(final_image))

    # -----------------------------
    #   Google Drive ์—…๋กœ๋“œ
    # -----------------------------
    upload_file_to_drive(drive, DRIVE_FOLDER_ID, txt_filename_local, txt_filename_local)
    upload_file_to_drive(drive, DRIVE_FOLDER_ID, png_filename_local, png_filename_local)
    upload_file_to_drive(drive, DRIVE_FOLDER_ID, jpg_filename_local, jpg_filename_local)

    
     # ๊ทธ๋ผ๋””์˜ค์—์„œ ๋ณด์—ฌ์ค„ ์ถœ๋ ฅ(์ด๋ฏธ์ง€)๊ณผ,
    print(type(final_image))
    return final_image

with gr.Blocks(css=css_code) as interface:
    gr.Markdown("<h1 style='font-size:30px;'>์ƒˆ๋กœ์šด ํ‹ฐ๋‹ˆํ•‘์ด ๋‚˜ํƒ€๋‚ฌ๋‹ค!</h1>")
    gr.Markdown("ํ•˜ํŠธ๋กœ์ฆˆ ๋ฒ ์ด์ปค๋ฆฌ์— ๋“ค์–ด์„  ๋‹น์‹ .")
    gr.Markdown("๊ทธ ์ˆœ๊ฐ„, ์†๋ฐ”๋‹ฅ๋งŒํ•œ ๋ฌด์–ธ๊ฐ€๊ฐ€ ๋น ๋ฅด๊ฒŒ ๋„๋ง์นœ๋‹ค!")
    gr.Image("teenie_runaway.png")
    gr.Markdown("์ €๊ฑดโ€ฆ ๋ถ„๋ช… ํ‹ฐ๋‹ˆํ•‘!")
    gr.Markdown("์บ์น˜ํ•˜๊ธฐ ์œ„ํ•ด ๋กœ๋ฏธ์—๊ฒŒ ๋‹น์žฅ ์•Œ๋ ค์•ผ ํ•ด.")
    inp = gr.Textbox(label="์–ด๋–ค ํ‹ฐ๋‹ˆํ•‘์„ ๋ดค๋Š”์ง€ ์„ค๋ช…ํ•ด์ค˜.", placeholder="์˜ˆ: ์ผ์ฃผ์ผ ๋‚ด๋‚ด ์šด๋™๋งŒ ํ•˜๋Š” ํ—ฌ์Šค์— ๋ฏธ์นœ ํ‹ฐ๋‹ˆํ•‘")
    btn = gr.Button("๋กœ๋ฏธ์•ผ ์ฐพ์•„์ค˜!")

    gr.Markdown("๋กœ๋ฏธ๊ฐ€ ์—ด์‹ฌํžˆ ํ‹ฐ๋‹ˆํ•‘์„ ์ฐพ๊ณ  ์žˆ์–ด. 2๋ถ„์ •๋„ ๊ฑธ๋ฆฌ๋‹ˆ ์กฐ๊ธˆ๋งŒ ๊ธฐ๋‹ค๋ ค์ค˜!")
    out = gr.Image(label="๋กœ๋ฏธ๊ฐ€ ์ฐพ์•„๋‚ธ ํ‹ฐ๋‹ˆํ•‘", type="pil")  # interactive ์ œ๊ฑฐ
    gr.Markdown("๋‹คํ–‰ํžˆ ํ‹ฐ๋‹ˆํ•‘์„ ๋ฐœ๊ฒฌํ•œ ๋กœ๋ฏธ. ๋น ๋ฅด๊ฒŒ ์บ์น˜!")
    gr.Markdown("ํ”ผ๋ฆฌํ”ผ๋ฆฌ ์บ์น˜๋ง, ํ๋ธŒ ์†์œผ๋กœ!")
    
    #btn2 = gr.Button("ํ‹ฐ๋‹ˆํ•‘ ์บ์น˜!")
    #output_html = gr.HTML()

    btn.click(fn=generate_combined_response, inputs=inp, outputs=out)
    #btn2.click(fn=save_final_image, inputs=out, outputs=output_html)

    #gr.Markdown(
    #"""
    #---
    #### Contact Info
    #- **Instagram**: [@temuping](https://instagram.com/temuping)
    #- **Mail**: [temooping@gmail.com](mailto:temooping@gmail.com)
    #"""
    #)

# ์•ฑ ์‹คํ–‰
if __name__ == "__main__":
    interface.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", 7860)), share=True)