File size: 28,720 Bytes
9d89d1c
 
 
 
 
 
2360382
9d89d1c
 
 
 
 
 
 
 
 
 
2360382
9d89d1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2360382
9d89d1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2360382
 
9d89d1c
 
2360382
 
9d89d1c
 
2360382
 
9d89d1c
2360382
9d89d1c
2360382
9d89d1c
 
 
 
 
 
 
 
2360382
9d89d1c
 
 
9013d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d89d1c
9013d8b
9d89d1c
 
 
 
 
 
 
 
 
 
9013d8b
9d89d1c
9013d8b
 
 
9d89d1c
9013d8b
 
 
9d89d1c
 
9013d8b
9d89d1c
 
9013d8b
 
 
 
 
9d89d1c
9013d8b
9d89d1c
9013d8b
9d89d1c
 
9013d8b
9d89d1c
 
9013d8b
 
 
 
 
 
 
 
 
 
9d89d1c
9013d8b
9d89d1c
9013d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d89d1c
 
9013d8b
9d89d1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9013d8b
 
 
 
 
 
9d89d1c
 
 
 
 
9013d8b
9d89d1c
9013d8b
9d89d1c
9013d8b
 
 
 
 
 
 
9d89d1c
 
 
 
9013d8b
9d89d1c
 
 
 
 
2360382
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
import gradio as gr
import numpy as np
import os
from huggingface_hub import login
from sentence_transformers import SentenceTransformer, util

# --- CONFIGURATION ---
# Centralized place for all settings and constants.

class Config:
    """Configuration settings for the application."""
    EMBEDDING_MODEL_ID = "google/embeddinggemma-300M"
    PROMPT_NAME = "STS"
    TOP_K = 5
    HF_TOKEN = os.getenv('HF_TOKEN')


# --- FONT DATA ---
# Comprehensive font dataset with descriptions for mood matching.

FONT_DATA = [
    {
        "name": "Playfair Display",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&display=swap",
        "description": "Elegant, sophisticated, editorial, high-contrast serif with dramatic flair, perfect for luxury brands and fashion magazines"
    },
    {
        "name": "Inter",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap",
        "description": "Modern, clean, professional, highly legible sans-serif designed for digital interfaces and contemporary design"
    },
    {
        "name": "Amatic SC",
        "family": "handwriting",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap",
        "description": "Playful, casual, handwritten, fun, child-like, informal font perfect for creative and whimsical projects"
    },
    {
        "name": "Crimson Text",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600&display=swap",
        "description": "Classical, scholarly, academic, readable serif inspired by old-style typefaces, ideal for books and literature"
    },
    {
        "name": "Roboto",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap",
        "description": "Friendly, approachable, geometric sans-serif with a mechanical skeleton, widely used in digital applications"
    },
    {
        "name": "Dancing Script",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400;700&display=swap",
        "description": "Romantic, flowing, elegant script font perfect for wedding invitations, greeting cards, and feminine designs"
    },
    {
        "name": "Oswald",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Oswald:wght@300;400;600&display=swap",
        "description": "Bold, condensed, impactful sans-serif with strong presence, ideal for headlines and masculine designs"
    },
    {
        "name": "Lora",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Lora:wght@400;600&display=swap",
        "description": "Warm, friendly, contemporary serif with calligraphic roots, perfect for body text and storytelling"
    },
    {
        "name": "Montserrat",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;600&display=swap",
        "description": "Urban, modern, versatile sans-serif inspired by Buenos Aires signage, great for branding and corporate use"
    },
    {
        "name": "Pacifico",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Pacifico&display=swap",
        "description": "Surfing, California, retro, casual script font with beach vibes and laid-back summer feeling"
    },
    {
        "name": "Source Code Pro",
        "family": "monospace",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@300;400;600&display=swap",
        "description": "Technical, programming, coding, monospaced font designed for developers and technical documentation"
    },
    {
        "name": "Merriweather",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400;700&display=swap",
        "description": "Traditional, readable, pleasant serif designed for comfortable reading on screens and in print"
    },
    {
        "name": "Abril Fatface",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Abril+Fatface&display=swap",
        "description": "Bold, dramatic, high-contrast display serif inspired by French and Italian typography, perfect for headlines"
    },
    {
        "name": "Great Vibes",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Great+Vibes&display=swap",
        "description": "Elegant, formal, calligraphic script with sophisticated curves, ideal for luxury and premium branding"
    },
    {
        "name": "Raleway",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Raleway:wght@300;400;600&display=swap",
        "description": "Sophisticated, thin, elegant sans-serif with distinctive 'W', perfect for fashion and high-end design"
    },
    {
        "name": "Fredoka One",
        "family": "display",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap",
        "description": "Friendly, rounded, playful display font perfect for children's content, toys, and fun applications"
    },
    {
        "name": "Libre Baskerville",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Libre+Baskerville:wght@400;700&display=swap",
        "description": "Classic, traditional, scholarly serif based on American Type Founder's Baskerville, perfect for academic texts"
    },
    {
        "name": "Poppins",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap",
        "description": "Geometric, modern, friendly sans-serif with circular forms, popular for contemporary web design"
    },
    {
        "name": "Lobster",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Lobster&display=swap",
        "description": "Bold, retro, vintage script font with a 1950s diner feel, perfect for nostalgic and Americana designs"
    },
    {
        "name": "Open Sans",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600&display=swap",
        "description": "Neutral, friendly, optimistic sans-serif designed for legibility across interfaces, print, and web"
    },
    {
        "name": "Shadows Into Light",
        "family": "handwriting",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Shadows+Into+Light&display=swap",
        "description": "Casual, handwritten, personal font that feels like natural handwriting with a marker or pen"
    },
    {
        "name": "Creepster",
        "family": "display",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Creepster&display=swap",
        "description": "Horror, scary, Halloween, gothic font with dripping effect, perfect for spooky and thriller themes"
    },
    {
        "name": "Righteous",
        "family": "display",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Righteous&display=swap",
        "description": "Futuristic, sci-fi, technology, bold display font with unique character shapes for modern designs"
    },
    {
        "name": "Satisfy",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Satisfy&display=swap",
        "description": "Casual, relaxed, handwritten script with natural flow, perfect for personal and informal communications"
    },
    {
        "name": "Anton",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Anton&display=swap",
        "description": "Bold, condensed, impactful sans-serif perfect for headlines, posters, and attention-grabbing text"
    },
    {
        "name": "Courgette",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Courgette&display=swap",
        "description": "French, bistro, cafΓ©, elegant script font with continental European charm and sophistication"
    },
    {
        "name": "Indie Flower",
        "family": "handwriting",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Indie+Flower&display=swap",
        "description": "Indie, hipster, handwritten font with quirky personality, perfect for creative and artistic projects"
    },
    {
        "name": "PT Serif",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=PT+Serif:wght@400;700&display=swap",
        "description": "Russian, Cyrillic, transitional serif with excellent readability for both Latin and Cyrillic scripts"
    },
    {
        "name": "Questrial",
        "family": "sans-serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Questrial&display=swap",
        "description": "Simple, clean, minimal sans-serif with subtle quirks, perfect for modern and understated designs"
    },
    {
        "name": "Bangers",
        "family": "display",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Bangers&display=swap",
        "description": "Comic book, superhero, pop art font inspired by mid-20th century comic books and advertisements"
    },
    {
        "name": "Sacramento",
        "family": "script",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Sacramento&display=swap",
        "description": "Monoline, cursive script with vintage charm, perfect for elegant and sophisticated branding"
    },
    {
        "name": "Bitter",
        "family": "serif",
        "google_fonts_url": "https://fonts.googleapis.com/css2?family=Bitter:wght@400;700&display=swap",
        "description": "Contemporary, slab serif with slight contrast, designed for comfortable reading in long texts"
    }
]


# --- CORE LOGIC ---
# Encapsulated in a class to manage state (model, embeddings) cleanly.

class FontMoodGenerator:
    """Handles model loading, embedding generation, and font palette creation."""

    def __init__(self, config: Config, font_data: list[dict[str, any]]):
        """Initializes the generator, logs in, and loads necessary assets."""
        self.config = config
        self.font_data = font_data
        self._login_to_hf()
        self.embedding_model = self._load_model()
        self.font_embeddings = self._precompute_font_embeddings()

    def _login_to_hf(self):
        """Logs into Hugging Face Hub if a token is provided."""
        if self.config.HF_TOKEN:
            print("Logging into Hugging Face Hub...")
            login(token=self.config.HF_TOKEN)
        else:
            print("HF_TOKEN not found. Proceeding without login.")
            print("Note: This may fail if the model is gated.")

    def _load_model(self) -> SentenceTransformer:
        """Loads the Sentence Transformer model."""
        print(f"Initializing embedding model: {self.config.EMBEDDING_MODEL_ID}...")
        try:
            return SentenceTransformer(self.config.EMBEDDING_MODEL_ID)
        except Exception as e:
            print(f"Error loading model: {e}")
            raise

    def _precompute_font_embeddings(self) -> np.ndarray:
        """Generates and stores embeddings for the font descriptions."""
        print("Pre-computing embeddings for font palette...")
        font_texts = [
            f"{font['name']}, {font['description']}"
            for font in self.font_data
        ]
        embeddings = self.embedding_model.encode(
            font_texts,
            prompt_name=self.config.PROMPT_NAME
        )
        print("Embeddings computed successfully.")
        return embeddings

    def _format_palette_as_html(self, top_hits: list[dict[str, any]]) -> str:
        """Formats the top font hits into a displayable HTML string."""
        if not top_hits:
            return "<p>Could not generate a font palette. Please try another mood.</p>"

        # Sample texts for different font types
        sample_texts = [
            "The Quick Brown Fox Jumps Over The Lazy Dog",
            "Sphinx of black quartz, judge my vow",
            "How vexingly quick daft zebras jump!",
            "Pack my box with five dozen liquor jugs",
            "Waltz, bad nymph, for quick jigs vex"
        ]

        cards_html = ""
        for i, hit in enumerate(top_hits):
            font_info = self.font_data[hit['corpus_id']]
            font_name = font_info['name']
            font_family = font_info['family']
            score = hit['score']
            sample_text = sample_texts[i % len(sample_texts)]

            cards_html += f"""
            <div class="font-card">
                <div class="font-header">
                    <h3>{font_name}</h3>
                    <span class="font-score">Score: {score:.2f}</span>
                </div>
                <div class="font-sample" style="font-family: '{font_name}', {font_family};">
                    {sample_text}
                </div>
                <div class="font-details">
                    <span class="font-family">{font_family.title()}</span>
                    <span class="font-description">{font_info['description'][:100]}...</span>
                </div>
            </div>
            """
        return f"<div class='font-palette-container'>{cards_html}</div>"

    def _create_font_imports_css(self, top_hits: list[dict[str, any]]) -> str:
        """Generates CSS imports for the selected fonts."""
        if not top_hits:
            return ""

        imports = []
        seen_urls = set()
        
        for hit in top_hits:
            font_info = self.font_data[hit['corpus_id']]
            google_fonts_url = font_info['google_fonts_url']
            
            if google_fonts_url not in seen_urls:
                imports.append(f"@import url('{google_fonts_url}');")
                seen_urls.add(google_fonts_url)

        return "\n".join(imports)

    def _create_dynamic_theme_css(self, top_hits: list[dict[str, any]]) -> str:
        """Generates a <style> block to apply fonts to different UI elements."""
        if not top_hits:
            return ""

        font_imports = self._create_font_imports_css(top_hits)
        
        css_rules = []
        
        # Apply different fonts to different elements
        if len(top_hits) >= 1:
            primary_font = self.font_data[top_hits[0]['corpus_id']]['name'].replace("'", "\\'")
            css_rules.append(f"h1, h2, h3, .gr-button-primary {{ font-family: '{primary_font}', sans-serif !important; }}")
        
        if len(top_hits) >= 2:
            secondary_font = self.font_data[top_hits[1]['corpus_id']]['name'].replace("'", "\\'")
            css_rules.append(f".gr-textbox input, .gr-textbox textarea {{ font-family: '{secondary_font}', sans-serif !important; }}")
        
        if len(top_hits) >= 3:
            tertiary_font = self.font_data[top_hits[2]['corpus_id']]['name'].replace("'", "\\'")
            css_rules.append(f".gr-button-secondary {{ font-family: '{tertiary_font}', sans-serif !important; }}")

        css_rules_str = "\n            ".join(css_rules)

        css = f"""<style>
            {font_imports}
            
            {css_rules_str}
            
            /* Custom animations for font changes */
            * {{
                transition: font-family 0.3s ease-in-out;
            }}
        </style>"""

        return css

    def _create_css_code_output(self, top_hits: list[dict[str, any]]) -> str:
        """Creates exportable CSS code for users."""
        if not top_hits:
            return ""
        
        font_imports = self._create_font_imports_css(top_hits)
        
        css_code = f"""/* Generated Font Palette CSS */
{font_imports}

/* Font Variables */
:root {{"""
        
        for i, hit in enumerate(top_hits):
            font_info = self.font_data[hit['corpus_id']]
            font_name = font_info['name']
            css_code += f"""
    --font-{i+1}: '{font_name}', {font_info['family']};"""
        
        css_code += """
}

/* Usage Examples */
.heading { font-family: var(--font-1); }
.body-text { font-family: var(--font-2); }
.accent { font-family: var(--font-3); }"""
        
        return css_code

    def generate_palette(self, mood_text: str) -> tuple[str, list[dict[str, any]]]:
        """Generates font palette and returns both HTML and raw data."""
        if not mood_text or not mood_text.strip():
            return "<p>Please enter a mood or a description.</p>", []

        mood_embedding = self.embedding_model.encode(
            mood_text,
            prompt_name=self.config.PROMPT_NAME
        )
        top_hits = util.semantic_search(
            mood_embedding, self.font_embeddings, top_k=self.config.TOP_K
        )[0]

        palette_html = self._format_palette_as_html(top_hits)
        return palette_html, top_hits

    def apply_theme(self, top_hits: list[dict[str, any]]) -> str:
        """Applies the theme CSS."""
        return self._create_dynamic_theme_css(top_hits)

    def generate_css_code(self, top_hits: list[dict[str, any]]) -> str:
        """Generates exportable CSS code."""
        return self._create_css_code_output(top_hits)


# --- GRADIO UI WITH WALKTHROUGH ---

def create_ui(generator: FontMoodGenerator):
    """Creates the Gradio web interface with Walkthrough."""
    
    # Shared state to store generated fonts across steps
    font_state = gr.State([])
    
    with gr.Blocks(theme="ocean") as demo:
        # Dynamic CSS output
        dynamic_css_output = gr.HTML()
        
        gr.Markdown("""
            # πŸ“ Font Mood Generator
            Follow the steps below to generate and apply a personalized font palette based on your mood or description.
        """)

        with gr.Walkthrough(selected=0) as walkthrough:
            
            # STEP 1: Input Mood
            with gr.Step("🎯 Describe Your Mood", id=0):
                gr.Markdown("""
                    ### Step 1: Tell us about your mood or vision
                    Describe the feeling, atmosphere, or aesthetic you're aiming for. 
                    Be as detailed as you like - the more descriptive, the better the results!
                """)
                
                mood_input = gr.Textbox(
                    value="Elegant wedding invitation with vintage charm",
                    label="Enter Your Mood or Scene",
                    info="Examples: 'Modern tech startup', 'Playful children's book', 'Gothic horror movie'",
                    lines=3
                )
                
                gr.Examples(
                    [
                        "Elegant wedding invitation with vintage charm",
                        "Modern tech startup with clean aesthetics", 
                        "Playful children's book with whimsical characters",
                        "Horror movie poster with scary atmosphere",
                        "Luxury fashion brand with sophisticated appeal",
                        "Retro 1950s diner with nostalgic vibes",
                    ],
                    inputs=mood_input,
                )
                
                generate_btn = gr.Button("Generate Font Palette β†’", variant="primary", size="lg")
                
                def generate_and_move(mood_text):
                    palette_html, top_hits = generator.generate_palette(mood_text)
                    return palette_html, top_hits, gr.Walkthrough(selected=1)
                
                generate_btn.click(
                    fn=generate_and_move,
                    inputs=mood_input,
                    outputs=[gr.State(), font_state, walkthrough]
                )
            
            # STEP 2: Review Generated Fonts
            with gr.Step("🎨 Review Your Font Palette", id=1):
                gr.Markdown("""
                    ### Step 2: Review your generated fonts
                    Here are the fonts that best match your mood, ranked by similarity score.
                    Each font is scored based on how well it captures your described aesthetic.
                """)
                
                palette_display = gr.HTML()
                
                def show_palette(palette_html):
                    return palette_html
                
                # Update palette when entering this step
                demo.load(
                    fn=show_palette,
                    inputs=gr.State(),
                    outputs=palette_display
                )
                
                with gr.Row():
                    back_to_input_btn = gr.Button("← Back to Input", variant="secondary")
                    apply_theme_btn = gr.Button("Apply Typography Theme β†’", variant="primary", size="lg")
                
                back_to_input_btn.click(
                    fn=lambda: gr.Walkthrough(selected=0),
                    outputs=walkthrough
                )
                
                def apply_and_move(top_hits):
                    theme_css = generator.apply_theme(top_hits)
                    return theme_css, gr.Walkthrough(selected=2)
                
                apply_theme_btn.click(
                    fn=apply_and_move,
                    inputs=font_state,
                    outputs=[dynamic_css_output, walkthrough]
                )
            
            # STEP 3: Experience the Typography
            with gr.Step("✨ Experience Your Typography", id=2):
                gr.Markdown("""
                    ### Step 3: See your fonts in action!
                    Notice how the entire interface has transformed to reflect your chosen aesthetic. 
                    The fonts from your palette are now applied throughout the UI.
                """)
                
                gr.Markdown("""
                    **πŸŽ‰ Your typography theme is now active!** 
                    
                    Look around the interface - the headings, buttons, and text inputs now use fonts from your generated palette. 
                    This gives you a real preview of how these fonts work together in a design context.
                    
                    **Font Roles:**
                    - **Primary Font**: Used for headings and primary buttons
                    - **Secondary Font**: Used for input fields and body text  
                    - **Accent Font**: Used for secondary buttons and highlights
                """)
                
                with gr.Row():
                    back_to_palette_btn = gr.Button("← Back to Palette", variant="secondary")
                    get_code_btn = gr.Button("Get CSS Code β†’", variant="primary", size="lg")
                
                back_to_palette_btn.click(
                    fn=lambda: gr.Walkthrough(selected=1),
                    outputs=walkthrough
                )
                
                get_code_btn.click(
                    fn=lambda: gr.Walkthrough(selected=3),
                    outputs=walkthrough
                )
            
            # STEP 4: Export and Use
            with gr.Step("πŸ’Ύ Export & Use Your Fonts", id=3):
                gr.Markdown("""
                    ### Step 4: Get the code and use your fonts
                    Copy the CSS code below to use your font palette in your own projects.
                """)
                
                css_code_output = gr.Code(
                    language="css", 
                    label="Your Font Palette CSS",
                    value="",
                    lines=15
                )
                
                def generate_css_code(top_hits):
                    return generator.generate_css_code(top_hits)
                
                # Generate CSS when entering this step
                demo.load(
                    fn=generate_css_code,
                    inputs=font_state,
                    outputs=css_code_output
                )
                
                gr.Markdown("""
                    **πŸš€ Next Steps:**
                    1. Copy the CSS code above
                    2. Include it in your website's stylesheet
                    3. Apply the font variables to your HTML elements
                    4. Enjoy your new typography!
                    
                    **πŸ’‘ Pro Tip:** You can also use individual Google Fonts links if you prefer to load fonts separately.
                """)
                
                with gr.Row():
                    start_over_btn = gr.Button("πŸ”„ Start Over", variant="secondary", size="lg")
                    
                def restart():
                    return "", [], gr.Walkthrough(selected=0)
                
                start_over_btn.click(
                    fn=restart,
                    outputs=[dynamic_css_output, font_state, walkthrough]
                )

        # Static CSS for font cards
        gr.HTML("""
            <style>
                .font-palette-container {
                    display: flex; flex-direction: column; gap: 15px;
                    align-items: center; width: 100%;
                }
                .font-card {
                    border: 2px solid #e0e0e0; border-radius: 12px;
                    padding: 20px; width: 90%; max-width: 600px;
                    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
                    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                    transition: all 0.3s ease;
                }
                .font-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 8px 20px rgba(0,0,0,0.15);
                }
                .font-header {
                    display: flex; justify-content: space-between;
                    align-items: center; margin-bottom: 15px;
                }
                .font-header h3 {
                    margin: 0; color: #2c3e50; font-size: 1.2em;
                }
                .font-score {
                    background: #3498db; color: white; padding: 4px 8px;
                    border-radius: 12px; font-size: 0.8em; font-weight: bold;
                }
                .font-sample {
                    font-size: 24px; line-height: 1.4; margin: 15px 0;
                    padding: 15px; background: #f8f9fa; border-radius: 8px;
                    border-left: 4px solid #3498db; color: #2c3e50;
                    min-height: 60px; display: flex; align-items: center;
                }
                .font-details {
                    display: flex; flex-direction: column; gap: 8px;
                }
                .font-family {
                    font-weight: bold; color: #7f8c8d; font-size: 0.9em;
                    text-transform: uppercase; letter-spacing: 1px;
                }
                .font-description {
                    color: #5d6d7e; font-size: 0.9em; line-height: 1.4;
                }
                
                /* Walkthrough styling enhancements */
                .gr-walkthrough {
                    border-radius: 12px;
                    overflow: hidden;
                }
            </style>
        """)

        gr.Markdown("""
            ----
            ## About This App
            
            This **Font Mood Generator** uses the new `gr.Walkthrough` component to create a guided, step-by-step experience for generating typography palettes. 
            
            The app is powered by [**EmbeddingGemma**](http://huggingface.co/google/embeddinggemma-300M), Google's text embedding model that understands the semantic meaning and emotional qualities of your descriptions to find matching fonts.
            
            **πŸ†• Walkthrough Features:**
            - **Guided Experience**: Step-by-step workflow for better user experience
            - **Progressive Disclosure**: Information and controls revealed when needed
            - **Visual Progress**: Clear indication of current step and progress
            - **Interactive Navigation**: Ability to go back and forth between steps
        """)

    return demo


if __name__ == "__main__":
    # Initialize application components
    generator = FontMoodGenerator(config=Config(), font_data=FONT_DATA)
    
    demo = create_ui(generator)
    demo.launch()