File size: 10,689 Bytes
3f6c6eb
 
f05400f
93d08c5
3f6c6eb
 
93d08c5
f05400f
93d08c5
 
 
 
3f6c6eb
93d08c5
 
 
 
 
 
 
3f6c6eb
 
93d08c5
 
 
 
 
 
3f6c6eb
93d08c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f6c6eb
93d08c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f6c6eb
93d08c5
 
 
 
 
3f6c6eb
 
93d08c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f6c6eb
 
 
 
93d08c5
 
 
 
 
 
3f6c6eb
 
93d08c5
 
 
 
f561a3b
93d08c5
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from models import generate_image, MODEL_ID
from config import APPLE_TENCENT_THEME
from typing import Optional

def create_ui():
    """Create the main application UI with Hugging Face OAuth authentication"""
    with gr.Blocks(title=f"Tencent HunyuanImage-3.0 Demo", theme=APPLE_TENCENT_THEME) as demo:
        # State to track authentication
        user_profile_state = gr.State(value=None)
        
        # Header with login button
        with gr.Row():
            with gr.Column(scale=3):
                gr.HTML(
                    f"<div style='text-align: center; max-width: 700px; margin: 0 auto;'>"
                    f"<h1>Tencent {MODEL_ID.split('/')[-1]}</h1>"
                    f"<p>Generate images using Tencent's state-of-the-art model hosted by FAL AI.</p>"
                    f"Built with <a href='https://huggingface.co/spaces/akhaliq/anycoder' target='_blank'>anycoder</a>"
                    f"</div>"
                )
            with gr.Column(scale=1):
                # Login button - shows "Sign in with Hugging Face" when logged out, "Logout (username)" when logged in
                login_button = gr.LoginButton(
                    value="Sign in with Hugging Face",
                    logout_value="Logout ({})",
                    size="lg",
                    variant="huggingface"
                )
        
        # User info display
        user_info = gr.Markdown("", visible=False)
        
        # Main interface container - hidden until authenticated
        with gr.Group(visible=False) as main_interface:
            with gr.Row():
                with gr.Column(scale=1):
                    prompt_input = gr.Textbox(
                        label="Prompt",
                        placeholder="e.g., A detailed watercolor painting of a small red fox sleeping on a pile of autumn leaves.",
                        lines=4
                    )
                    
                    with gr.Row():
                        generate_btn = gr.Button("🎨 Generate Image", variant="primary", scale=2)
                        clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary", scale=1)
                    
                    # Additional settings in an accordion
                    with gr.Accordion("βš™οΈ Advanced Settings", open=False):
                        gr.Markdown("""
                        Advanced settings are not implemented in this demo.
                        You can add parameters like:
                        - Image size
                        - Number of steps
                        - Guidance scale
                        - Seed
                        """)
                        
                with gr.Column(scale=1):
                    output_image = gr.Image(
                        label="Generated Image",
                        height=512,
                        width=512,
                        interactive=False,
                        show_download_button=True
                    )
                    
                    # Generation status
                    status_text = gr.Markdown("Ready to generate...", visible=True)

            # Example prompts
            gr.Examples(
                examples=[
                    "A detailed watercolor painting of a small red fox sleeping on a pile of autumn leaves.",
                    "A futuristic cityscape at sunset with flying cars and neon lights",
                    "A serene Japanese garden with cherry blossoms and a koi pond",
                    "A steampunk mechanical owl perched on an ancient tree",
                    "An astronaut playing guitar on the moon with Earth in the background"
                ],
                inputs=prompt_input,
                outputs=[output_image, status_text],
                fn=lambda prompt: generate_with_status(prompt, user_profile_state.value),
                cache_examples=False,
                show_api=False,
            )
        
        # Welcome message for non-authenticated users
        welcome_message = gr.HTML(
            """
            <div style='text-align: center; max-width: 600px; margin: 50px auto; padding: 30px; 
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                        border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.2);'>
                <h2 style='color: white; margin-bottom: 20px;'>🎨 Welcome to HunyuanImage-3.0</h2>
                <p style='color: rgba(255,255,255,0.9); font-size: 16px; line-height: 1.6;'>
                    Sign in with your Hugging Face account to start generating amazing images 
                    with Tencent's state-of-the-art AI model.
                </p>
                <div style='margin-top: 30px; padding: 20px; background: rgba(255,255,255,0.1); 
                            border-radius: 10px;'>
                    <p style='color: white; margin: 0;'>
                        <strong>✨ Features:</strong><br>
                        β€’ High-quality image generation<br>
                        β€’ Easy-to-use interface<br>
                        β€’ Multiple example prompts<br>
                        β€’ Download generated images
                    </p>
                </div>
                <p style='color: rgba(255,255,255,0.8); font-size: 14px; margin-top: 20px;'>
                    Click the "Sign in with Hugging Face" button above to get started
                </p>
            </div>
            """,
            visible=True
        )
        
        # Authentication handling functions
        def update_ui_on_auth(profile: gr.OAuthProfile | None) -> tuple:
            """Update UI based on authentication status"""
            if profile is None:
                # User is not authenticated
                return (
                    gr.update(visible=False),  # main_interface
                    gr.update(visible=True),   # welcome_message
                    "",                         # user_info
                    gr.update(visible=False),  # user_info visibility
                    None                        # user_profile_state
                )
            else:
                # User is authenticated
                user_text = f"### πŸ‘€ Welcome, {profile.name}!\n\n"
                if profile.username:
                    user_text += f"**Username:** @{profile.username}\n"
                if hasattr(profile, 'email') and profile.email:
                    user_text += f"**Email:** {profile.email}\n"
                
                return (
                    gr.update(visible=True),   # main_interface
                    gr.update(visible=False),  # welcome_message
                    user_text,                  # user_info
                    gr.update(visible=True),   # user_info visibility
                    profile                     # user_profile_state
                )
        
        def generate_with_status(prompt: str, profile: gr.OAuthProfile | None) -> tuple:
            """Generate image with status updates and user verification"""
            if profile is None:
                return None, "⚠️ Please sign in to generate images!"
            
            if not prompt:
                return None, "⚠️ Please enter a prompt!"
            
            try:
                # You can log user activity here if needed
                print(f"User {profile.username} is generating an image with prompt: {prompt[:50]}...")
                
                # Generate the image
                image = generate_image(prompt)
                
                return image, "βœ… Image generated successfully!"
                
            except Exception as e:
                return None, f"❌ Error: {str(e)}"
        
        def clear_interface():
            """Clear the interface"""
            return "", None, "Ready to generate..."
        
        # Load event to check authentication status
        demo.load(
            fn=update_ui_on_auth,
            inputs=None,
            outputs=[main_interface, welcome_message, user_info, user_info, user_profile_state],
            queue=False,
            show_api=False,
        )
        
        # Login button click event (also handles logout)
        login_button.click(
            fn=update_ui_on_auth,
            inputs=None,
            outputs=[main_interface, welcome_message, user_info, user_info, user_profile_state],
            queue=False,
            show_api=False,
        )
        
        # Generate button event
        generate_btn.click(
            fn=lambda prompt, profile: generate_with_status(prompt, profile),
            inputs=[prompt_input, user_profile_state],
            outputs=[output_image, status_text],
            queue=False,
            show_api=False,
        )
        
        # Clear button event
        clear_btn.click(
            fn=clear_interface,
            inputs=[],
            outputs=[prompt_input, output_image, status_text],
            queue=False,
            show_api=False,
        )
        
        # Footer
        gr.HTML(
            """
            <div style='text-align: center; margin-top: 40px; padding: 20px; border-top: 1px solid #e0e0e0;'>
                <p style='color: #666; font-size: 14px;'>
                    This demo uses Hugging Face OAuth for secure authentication. 
                    Your session will remain active until you logout.
                    <br>For the best results, provide detailed prompts with specific descriptions.
                </p>
            </div>
            """
        )

    return demo

# Additional helper function for logging/tracking (optional)
def log_user_activity(profile: gr.OAuthProfile, action: str, details: str = ""):
    """Log user activity for analytics or monitoring"""
    if profile:
        print(f"[{action}] User: {profile.username}, Name: {profile.name}, Details: {details}")

if __name__ == "__main__":
    app = create_ui()
    
    # Launch the app
    # Note: OAuth features work best when deployed on Hugging Face Spaces
    # For local development, it will use the local HF account (via hf auth login)
    app.launch(
        show_api=False,
        enable_monitoring=False,
        quiet=True,
        share=False,  # Set to True if you want to create a public link
        server_name="0.0.0.0",  # Change to "0.0.0.0" to allow external access
        server_port=7860,  # Default Gradio port
    )
    
    # Note: When deploying to Hugging Face Spaces, you can configure OAuth permissions
    # in the README file as described here: https://huggingface.co/docs/hub/en/spaces-oauth