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("

새로운 티니핑이 나타났다!

") 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)