import os import openai import gradio as gr from diffusers import StableDiffusionPipeline import torch # OpenAI API 키 설정 client = openai.Client(api_key=os.getenv("OPENAI_API_KEY")) # Stable Diffusion 모델 로드 (CPU 모드) base_model_id = "runwayml/stable-diffusion-v1-5" pipe = StableDiffusionPipeline.from_pretrained(base_model_id, torch_dtype=torch.float32).to("cpu") # LoRA 가중치 로드 함수 # adapter_config.json 파일이 없는 경우 기본 구성을 설정합니다. def load_lora_weights(pipeline, lora_model_path): config = { "lora_r": 16, # Rank of the low-rank matrix "lora_alpha": 32, # Scaling factor "lora_dropout": 0.1, # Dropout probability "bias": "none", # Bias configuration "task_type": "TEXT_TO_IMAGE" # Task type } # config를 기반으로 LoRA 가중치를 로드합니다. pipeline.load_lora_weights(lora_model_path, config=config) print("LoRA weights successfully loaded!") # LoRA 가중치 로드 lora_model_path = "./1211TeeniePing_Taesu-10.safetensors" load_lora_weights(pipe, lora_model_path) # 메모리 최적화 def optimize_pipeline(pipeline): pipeline.enable_attention_slicing() pipeline.enable_sequential_cpu_offload() return pipeline pipe = optimize_pipeline(pipe) # API 호출 함수 정의 def generate_response(user_prompt): try: # ChatCompletion 엔드포인트 사용 response = client.chat.completions.create( model="ft:gpt-4o-2024-08-06:personal::AdfXb935", # fine-tuned 모델 ID messages=[ {"role": "system", "content": ( "너는 아동 캐릭터를 기획하는데 일가견있는 캐릭터디자이너야. 너가 할일은 사람들이 원하는 캐릭터에 대한 설명을 주의깊게 이해한 뒤, 이를 바탕으로 아동 애니메이션 캐릭터인 티니핑의 캐릭터 컨셉을 디자인하는거야." "너가 할 일은 다음과 같아. 좋은 캐릭터 컨셉이 도출되면 20%의 보너스를 받게 될거야. " "과업 1. 주어진 설명에 대한 메타인지를 바탕으로 아이들이 따라하기 쉽고, 재밌게 말할 수 있는 캐릭터 이름의 어원을 정해. 이 때, 어원의 품사도 함께 고려해서 정해." "과업 2. 과업 1에서 도출된 어원을 바탕으로 티니핑의 이름을 지어. " "과업 3. 주어진 설명과 티니핑의 이름에 대한 메타인지를 바탕으로 티니핑이 사용하는 마법과 핵심 대사를 지어. " "과업 4. 이전 과업들에 대한 메타인지를 바탕으로 캐릭터의 머리 모양과 가지고 다닐 악세사리를 정해. " "과업 5. 마지막으로, 캐릭터의 몸 색상, 머리 색상, 악세사리 색상을 Hue, Saturation, Value로 정해. " "이제, 이를 종합해서 jsonl파일 형태로 제공해." 'jsonl 파일의 양식은 다음과 같아: {"Description": "000", "Etymology": "000", "Etymology.Type": "000", "Name": "000", "Magic": "000", "KeySentence": "000", "Body color": "[Hue: 00.0, Saturation: 0.00, Value: 0.00]", "Hair style": "000", "Hair color": "[Hue: 00.0, Saturation: 0.00, Value: 0.00]","Hand-held item": "000", "Hand-held item color": "[Hue: 00.0, Saturation: 0.00, Value: 0.00]"}' )}, {"role": "user", "content": user_prompt} ], timeout=15 ) # ChatCompletion 응답 텍스트 반환 return response.choices[0].message.content except openai.OpenAIError as e: # OpenAI 관련 에러 처리 return f"OpenAI API 오류: {str(e)}" except Exception as e: # 기타 에러 처리 return f"알 수 없는 오류 발생: {str(e)}" # 이미지 생성 함수 def generate_image(prompt): try: # Stable Diffusion을 사용해 이미지 생성 generator = torch.manual_seed(42) # 고정된 시드로 재현 가능하게 설정 image = pipe(prompt, num_inference_steps=20, guidance_scale=7.5).images[0] # steps 및 cfg_scale 조정 return image except Exception as e: return f"이미지 생성 중 오류 발생: {str(e)}" # Gradio 인터페이스 설정 def generate_combined_response(user_prompt): # GPT 응답 생성 gpt_response = generate_response(user_prompt) # GPT 응답을 텍스트로 출력하고 Stable Diffusion으로 이미지 생성 image = generate_image(gpt_response) return gpt_response, image interface = gr.Interface( fn=generate_combined_response, inputs=[ gr.Textbox( label="질문을 입력하세요", placeholder="예: 용감하고 씩씩한 티니핑을 만들어주세요!" ) ], outputs=[ gr.Textbox(label="GPT의 응답"), gr.Image(label="생성된 이미지") ], title="OpenAI API 기반 티니핑 생성기", description="OpenAI의 GPT-4와 Stable Diffusion을 사용하여 나만의 티니핑 캐릭터를 설계하고 이미지를 생성해보세요." ) # 앱 실행 if __name__ == "__main__": interface.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", 7860)), share=True)