File size: 10,439 Bytes
e8bac0f
ff1697a
e8bac0f
04e9db1
1f5b975
 
 
887c8af
 
633af1d
c4f57a0
04e9db1
633af1d
836d905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b62ce7
ff1697a
 
e8bac0f
1f5b975
a194516
2f577c6
1f5b975
d8bbd3a
836d905
633af1d
836d905
633af1d
 
 
d8bbd3a
836d905
d8bbd3a
836d905
d8bbd3a
836d905
d8bbd3a
836d905
d8bbd3a
 
 
836d905
d8bbd3a
836d905
d8bbd3a
 
887c8af
633af1d
836d905
633af1d
 
682535d
836d905
682535d
 
 
 
2f577c6
682535d
 
836d905
2f577c6
682535d
836d905
682535d
836d905
60dfb52
836d905
1f5b975
c4f57a0
836d905
c4f57a0
 
ff1697a
263e495
ff1697a
 
8b62ce7
c4f57a0
 
 
 
 
 
8b62ce7
 
836d905
ff1697a
c97f523
887c8af
 
1f5b975
887c8af
 
c97f523
 
263e495
836d905
f91a6a4
a6549b1
1f5b975
633af1d
836d905
dcb78ae
 
 
 
 
682535d
5843541
dcb78ae
1c96884
dcb78ae
 
 
 
8a82794
1c96884
 
 
 
dc3cdae
1c96884
 
 
 
 
 
 
 
5843541
 
7a1a45e
 
 
 
 
c4f57a0
 
 
 
 
 
 
 
 
 
 
 
0dc0c33
 
 
 
 
91b37f6
 
 
 
 
780dba6
0dc0c33
91b37f6
0dc0c33
7a1a45e
c4f57a0
 
 
 
 
83746e4
2f577c6
 
633af1d
 
83746e4
836d905
 
 
 
 
 
 
 
 
 
 
 
d8bbd3a
633af1d
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
import gradio as gr
from gradio_client import Client
import os
import logging
from notion_client import Client as NotionClient
import requests
from datetime import datetime
from PIL import Image
import io
import sys

# ๋กœ๊น… ์„ค์ •
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', stream=sys.stdout)
logger = logging.getLogger(__name__)

try:
    import gradio as gr
    from gradio_client import Client
    import os
    from notion_client import Client as NotionClient
    import requests
    from datetime import datetime
    from PIL import Image
    import io
    logger.info("All modules imported successfully")
except ImportError as e:
    logger.error(f"Error importing modules: {e}")
    sys.exit(1)

# API ํด๋ผ์ด์–ธํŠธ ์„ค์ •
api_client = Client("http://211.233.58.202:7960/")

# Notion ํด๋ผ์ด์–ธํŠธ ์„ค์ •
NOTION_TOKEN = os.getenv("NOTION_TOKEN")
NOTION_DATABASE_ID = "88c9bdadcb2044129af77d5932e1a82a"

def test_notion_connection():
    logger.info("Starting Notion connection test")
    if not NOTION_TOKEN:
        logger.error("NOTION_TOKEN is not set. Please set the environment variable.")
        return False

    notion = NotionClient(auth=NOTION_TOKEN)
    try:
        logger.debug("Testing Notion connection...")
        user_info = notion.users.me()
        logger.info(f"Successfully connected to Notion. User info: {user_info}")
        
        logger.debug("Retrieving database info...")
        db_info = notion.databases.retrieve(database_id=NOTION_DATABASE_ID)
        logger.info(f"Successfully retrieved database info: {db_info}")
        
        return True
    except Exception as e:
        logger.error(f"Error connecting to Notion: {str(e)}")
        if hasattr(e, 'response'):
            logger.error(f"Notion API response: {e.response.text}")
        return False

def add_to_notion(prompt, image_path):
    if not notion:
        logger.warning("Notion integration is not available. Skipping add_to_notion.")
        return

    try:
        logger.debug(f"Adding to Notion - Prompt: {prompt}, Image Path: {image_path}")
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        new_page = {
            "Prompt": {"title": [{"text": {"content": prompt}}]},
            "Image": {"url": f"http://211.233.58.202:7960/file={image_path}"},
            "Date": {"date": {"start": now}}
        }
        logger.debug(f"New page properties: {new_page}")
        
        response = notion.pages.create(parent={"database_id": NOTION_DATABASE_ID}, properties=new_page)
        logger.info(f"Successfully added to Notion: {response}")
    except Exception as e:
        logger.error(f"Error adding to Notion: {str(e)}")
        if hasattr(e, 'response'):
            logger.error(f"Notion API response: {e.response.text}")

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:
            image_path = result[0]
            # Notion์— ์ถ”๊ฐ€
            add_to_notion(message, image_path)
            return Image.open(image_path)
        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"]
]

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("Starting application")
    logger.info(f"Notion Database ID: {NOTION_DATABASE_ID}")
    logger.info(f"Notion Token (first 5 chars): {NOTION_TOKEN[:5] if NOTION_TOKEN else 'Not set'}")
    
    notion_connection_successful = test_notion_connection()
    
    if notion_connection_successful:
        logger.info("Notion connection test passed. Starting Gradio interface...")
        notion = NotionClient(auth=NOTION_TOKEN)
    else:
        logger.error("Failed to connect to Notion. The application will continue without Notion integration.")
        notion = None
    
    demo.launch()