import gradio as gr from gradio_client import Client import os import logging import requests from PIL import Image import io import base64 # 로깅 설정 logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # API 클라이언트 설정 api_client = Client("http://211.233.58.202:7960/") # Webhook URL WEBHOOK_URL = "https://connect.pabbly.com/workflow/sendwebhookdata/IjU3NjUwNTY0MDYzMTA0MzE1MjZlNTUzYzUxM2Ei_pc" # Imgur 클라이언트 ID IMGUR_CLIENT_ID = "여기에_당신의_IMGUR_CLIENT_ID를_입력하세요" def upload_to_imgur(image_data): try: logger.debug(f"Image data type: {type(image_data)}") logger.debug(f"Image data length: {len(image_data)}") # 이미지 데이터를 PIL Image 객체로 변환 image = Image.open(io.BytesIO(image_data)) # PNG 형식으로 변환 buffered = io.BytesIO() image.save(buffered, format="PNG") # Base64로 인코딩 im_b64 = base64.b64encode(buffered.getvalue()).decode("utf-8") url = "https://api.imgur.com/3/image" payload = {'image': im_b64, 'type': 'base64'} headers = {'Authorization': f'Client-ID {IMGUR_CLIENT_ID}'} logger.debug("Sending request to Imgur API") response = requests.post(url, headers=headers, data=payload) logger.debug(f"Imgur API response status: {response.status_code}") logger.debug(f"Imgur API response content: {response.text}") response.raise_for_status() return response.json()['data']['link'] except Exception as e: logger.error(f"Failed to upload image to Imgur: {e}") if hasattr(e, 'response'): logger.error(f"Response content: {e.response.text}") return None def send_to_webhook(prompt, image_url): payload = { "prompt": prompt, "image": image_url } try: response = requests.post(WEBHOOK_URL, json=payload) response.raise_for_status() logger.info(f"Successfully sent data to webhook. Status code: {response.status_code}") except requests.exceptions.RequestException as e: logger.error(f"Failed to send data to webhook: {e}") def respond(message, seed, randomize_seed, width, height, guidance_scale, num_inference_steps): logger.info(f"Received message: {message}, seed: {seed}, randomize_seed: {randomize_seed}, " f"width: {width}, height: {height}, guidance_scale: {guidance_scale}, " f"num_inference_steps: {num_inference_steps}") try: # 이미지 생성 요청 result = api_client.predict( prompt=message, seed=seed, randomize_seed=randomize_seed, width=width, height=height, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, api_name="/infer_t2i" ) logger.info("API response received: %s", result) # 결과 확인 및 처리 if isinstance(result, tuple) and len(result) >= 1: local_image_path = result[0] # 이미지 파일을 메모리에 로드 with open(local_image_path, "rb") as f: image_data = f.read() # Imgur에 이미지 업로드 imgur_url = upload_to_imgur(image_data) if imgur_url: # Webhook으로 데이터 전송 send_to_webhook(message, imgur_url) return Image.open(io.BytesIO(image_data)) else: raise ValueError("Failed to upload image to Imgur") else: raise ValueError("Unexpected API response format") except Exception as e: logger.error("Error during API request: %s", str(e)) return "Failed to generate image due to an error." # ... (나머지 코드는 그대로 유지) css = """ footer { visibility: hidden; } """ # 이미지 생성을 위한 예제 프롬프트 examples = [ ["A glamorous young woman with long, wavy blonde hair and smokey eye makeup, posing in a luxury hotel room. She’s wearing a sparkly gold cocktail dress and holding up a white card with 'openfree.ai' written on it in elegant calligraphy. Soft, warm lighting creates a luxurious atmosphere. ", "q1.webp"], ["A fit male fitness influencer with short dark hair and stubble, standing shirtless in a modern gym. He has defined abs and arm muscles, and is holding a protein shake in one hand and a card that says 'openfree.ai' in the other. Bright, clean lighting highlights his physique.", "q2.webp"], ["A bohemian-style female travel blogger with sun-kissed skin and messy beach waves, sitting on a tropical beach at sunset. She’s wearing a flowy white sundress and holding up a weathered postcard with 'openfree.ai' scrawled on it. Golden hour lighting bathes the scene in warm tones. ", "q3.webp"], ["A trendy male fashion influencer with perfectly styled hair and designer stubble, posing on a city street. He’s wearing a tailored suit and holding up a sleek black business card with 'openfree.ai' printed in minimalist white font. The background shows blurred city lights, creating a chic urban atmosphere.", "q4.webp"], ["A fresh-faced young female beauty guru with freckles and natural makeup, sitting at a vanity covered in cosmetics. She’s wearing a pastel pink robe and holding up a makeup palette with 'openfree.ai' written on it in lipstick. Soft, flattering lighting enhances her radiant complexion. ", "q5.webp"], ["A stylish young woman with long, wavy ombre hair and winged eyeliner, posing in front of a neon-lit city skyline at night. She’s wearing a sleek black leather jacket over a sparkly crop top and holding up a holographic business card that says 'openfree.ai' in futuristic font. The card reflects the colorful neon lights, creating a cyberpunk aesthetic.", "q6.webp"], ["Create a surreal advertisement poster for a fictional time travel agency. The background should depict a swirling vortex of clock faces and historical landmarks from different eras. In the foreground, place large, bold text that reads “AI TOURS: YOUR PAST IS OUR FUTURE” in a retro-futuristic font. The text should appear to be partially disintegrating into particles that are being sucked into the time vortex. Include smaller text at the bottom with fictional pricing and the slogan “History is just a ticket away!”", "q7.webp"], ["Photo realistic scene inspired by LOTR: [A tiny red dragon sleeps curled up in a nest on a medieval wizard's table]. Shot with a macro lens (f/2.8, 50mm) and a Canon EOSR5, the soft focus captures [the cozy morning light filtering through a near by window]. The pastel colors and whimsical steam shapes enhance the serene atmosphere, evoking a DnD RPG setting. The image is rendered in 16K and 8K, highlighting [the intricate details and medieval charm].", "q8.webp"], ["썬글라스를 착용한 귀여운 강아지가 'Openfree.ai'라고 쓰여진 표지판을 들고있다.", "q9.webp"], ["미레적인 도시의 해지는 풍경", "q10.webp"], ["빨간색 박스에 'openfree.ai'라고 글씨가 쓰여있고, 그위에 강아지와 고양이가 앉아있다.", "q11.webp"], ["로봇이 공사장에서 작업중이다. 배경에 'Coming soon~'라는 글자가 쓰여있다.", "q20.webp"], ["A serene landscape with mountains in the background and a clear lake in the foreground.", "q12.webp"], ["A street scene from Tokyo at night, vibrant and full of lights.", "q13.webp"], ["An astronaut riding a horse on Mars.", "q14.webp"], ["A surreal painting of a tree growing books.", "q15.webp"], ["A cottage in a snowy forest, lit by warm lights.", "q16.webp"], ["A still life of various fruits and a wine glass on a table.", "q17.webp"], ["A digital artwork of a neon-lit alley in a cyberpunk city.", "q18.webp"], ["A fantasy map of a fictional world, with detailed terrain and cities.", "q19.webp"] ] def use_prompt(prompt): return prompt with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as demo: with gr.Row(): input_text = gr.Textbox(label="Enter your prompt for image generation") output_image = gr.Image(label="Generated Image") with gr.Row(): seed = gr.Slider(minimum=0, maximum=1000000, step=1, label="Seed", value=123) randomize_seed = gr.Checkbox(label="Randomize Seed", value=False) with gr.Row(): width = gr.Slider(minimum=256, maximum=1024, step=64, label="Width", value=1024) height = gr.Slider(minimum=256, maximum=1024, step=64, label="Height", value=576) with gr.Row(): guidance_scale = gr.Slider(minimum=1, maximum=20, step=0.1, label="Guidance Scale", value=5) num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Number of Inference Steps", value=28) with gr.Row(): for prompt, image_file in examples: with gr.Column(): gr.Image(image_file, label=prompt[:50] + "...") # 프롬프트의 처음 50자만 표시 gr.Button("Use this prompt").click( fn=use_prompt, inputs=[], outputs=input_text, api_name=False ).then( lambda x=prompt: x, inputs=[], outputs=input_text ) input_text.submit( fn=respond, inputs=[input_text, seed, randomize_seed, width, height, guidance_scale, num_inference_steps], outputs=output_image ) if __name__ == "__main__": logger.info(f"Starting application with Imgur Client ID: {IMGUR_CLIENT_ID[:5]}...") demo.launch()