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b6
 
dd5d6cc
968f595
dd5d6cc
968f595
 
 
 
dd5d6cc
 
1a0c9b6
968f595
 
 
 
dd5d6cc
 
 
 
 
 
1a0c9b6
968f595
dd5d6cc
1a0c9b6
dd5d6cc
968f595
 
 
dd5d6cc
 
 
0e14842
dd5d6cc
968f595
 
 
 
 
 
 
 
 
 
 
 
dd5d6cc
968f595
 
9d997d8
dd5d6cc
 
 
 
 
 
 
 
9dace64
dd5d6cc
 
 
 
 
 
 
 
 
 
 
 
0e14842
dd5d6cc
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
# app.py
import os
import base64
import streamlit as st
from gradio_client import Client
from dotenv import load_dotenv
from pathlib import Path
import json
import hashlib
import time
from typing import Dict, Any

# Load environment variables
load_dotenv()
HF_TOKEN = os.getenv("HF_TOKEN")

# Cache directory setup
CACHE_DIR = Path("./cache")
CACHE_DIR.mkdir(exist_ok=True)

# Cached example diagrams
CACHED_EXAMPLES = {
    "literacy_mental": {
        "title": "Literacy Mental Map",
        "prompt": """A handrawn colorful mind map diagram, rugosity drawn lines, clear shapes, brain silhouette, text areas. must include the texts 
        LITERACY/MENTAL
        β”œβ”€β”€ PEACE [Dove Icon]
        β”œβ”€β”€ HEALTH [Vitruvian Man ~60px]
        β”œβ”€β”€ CONNECT [Brain-Mind Connection Icon]
        β”œβ”€β”€ INTELLIGENCE
        β”‚   └── EVERYTHING [Globe Icon ~50px]
        └── MEMORY
            β”œβ”€β”€ READING [Book Icon ~40px]
            β”œβ”€β”€ SPEED [Speedometer Icon]
            └── CREATIVITY
                └── INTELLIGENCE [Lightbulb + Infinity ~30px]""",
        "width": 1024,
        "height": 1024,
        "seed": 1872187377,
        "cache_path": "literacy_mental.png"
    }
}

DIAGRAM_EXAMPLES = [
    {
        "title": "Project Management Flow",
        "prompt": """A handrawn colorful mind map diagram, rugosity drawn lines, clear shapes, project management flow.
        PROJECT MANAGEMENT
        β”œβ”€β”€ INITIATION [Rocket Icon]
        β”œβ”€β”€ PLANNING [Calendar Icon]
        β”œβ”€β”€ EXECUTION [Gear Icon]
        β”œβ”€β”€ MONITORING
        β”‚   └── CONTROL [Dashboard Icon]
        └── CLOSURE [Checkmark Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Digital Marketing Strategy",
        "prompt": """A handrawn colorful mind map diagram, rugosity drawn lines, modern style, marketing concept.
        DIGITAL MARKETING
        β”œβ”€β”€ SEO [Magnifying Glass]
        β”œβ”€β”€ SOCIAL MEDIA [Network Icon]
        β”œβ”€β”€ CONTENT
        β”‚   β”œβ”€β”€ BLOG [Document Icon]
        β”‚   └── VIDEO [Play Button]
        └── ANALYTICS [Graph Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Software Development Lifecycle",
        "prompt": """A handrawn colorful mind map diagram, technical style, software development flow.
        SDLC
        β”œβ”€β”€ REQUIREMENTS [Document Icon]
        β”œβ”€β”€ DESIGN [Blueprint Icon]
        β”œβ”€β”€ DEVELOPMENT [Code Icon]
        β”œβ”€β”€ TESTING
        β”‚   β”œβ”€β”€ UNIT [Checkbox Icon]
        β”‚   └── INTEGRATION [Puzzle Icon]
        └── DEPLOYMENT [Rocket Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Environmental Sustainability",
        "prompt": """A handrawn colorful mind map diagram, nature-inspired style, environmental concept.
        ECO-FRIENDLY
        β”œβ”€β”€ REDUCE [Minus Icon]
        β”œβ”€β”€ REUSE [Cycle Icon]
        β”œβ”€β”€ RECYCLE [Triangle Icon]
        └── ENERGY
            β”œβ”€β”€ SOLAR [Sun Icon]
            └── WIND [Windmill Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Business Strategy",
        "prompt": """A handrawn colorful mind map diagram, professional style, business planning.
        STRATEGY
        β”œβ”€β”€ VISION [Eye Icon]
        β”œβ”€β”€ MISSION [Target Icon]
        β”œβ”€β”€ GOALS
        β”‚   β”œβ”€β”€ SHORT-TERM [Clock Icon]
        β”‚   └── LONG-TERM [Calendar Icon]
        └── METRICS [Graph Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Health & Wellness",
        "prompt": """A handrawn colorful mind map diagram, wellness-focused style, health aspects.
        WELLNESS
        β”œβ”€β”€ PHYSICAL [Dumbbell Icon]
        β”œβ”€β”€ MENTAL [Brain Icon]
        β”œβ”€β”€ NUTRITION [Apple Icon]
        └── SLEEP
            β”œβ”€β”€ QUALITY [Star Icon]
            └── DURATION [Clock Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Innovation Process",
        "prompt": """A handrawn colorful mind map diagram, creative style, innovation flow.
        INNOVATION
        β”œβ”€β”€ IDEATION [Lightbulb Icon]
        β”œβ”€β”€ RESEARCH [Magnifier Icon]
        β”œβ”€β”€ PROTOTYPING [Tools Icon]
        └── TESTING
            β”œβ”€β”€ FEEDBACK [Chat Icon]
            └── ITERATION [Cycle Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Data Science Workflow",
        "prompt": """A handrawn colorful mind map diagram, technical style, data science process.
        DATA SCIENCE
        β”œβ”€β”€ COLLECTION [Database Icon]
        β”œβ”€β”€ CLEANING [Filter Icon]
        β”œβ”€β”€ ANALYSIS [Graph Icon]
        └── VISUALIZATION
            β”œβ”€β”€ CHARTS [Bar Chart Icon]
            └── REPORTS [Document Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Product Development",
        "prompt": """A handrawn colorful mind map diagram, product-focused style, development stages.
        PRODUCT
        β”œβ”€β”€ RESEARCH [Magnifier Icon]
        β”œβ”€β”€ DESIGN [Pencil Icon]
        β”œβ”€β”€ BUILD [Tools Icon]
        └── LAUNCH
            β”œβ”€β”€ TESTING [Checkbox Icon]
            └── RELEASE [Rocket Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Time Management",
        "prompt": """A handrawn colorful mind map diagram, organizational style, time concepts.
        TIME
        β”œβ”€β”€ PLANNING [Calendar Icon]
        β”œβ”€β”€ PRIORITIES [Star Icon]
        β”œβ”€β”€ EXECUTION [Clock Icon]
        └── REVIEW
            β”œβ”€β”€ DAILY [Sun Icon]
            └── WEEKLY [Moon Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Customer Journey",
        "prompt": """A handrawn colorful mind map diagram, user-centric style, customer experience.
        CUSTOMER
        β”œβ”€β”€ AWARENESS [Eye Icon]
        β”œβ”€β”€ CONSIDERATION [Think Icon]
        β”œβ”€β”€ PURCHASE [Cart Icon]
        └── LOYALTY
            β”œβ”€β”€ SUPPORT [Headset Icon]
            └── FEEDBACK [Star Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Financial Planning",
        "prompt": """A handrawn colorful mind map diagram, finance-focused style, money management.
        FINANCE
        β”œβ”€β”€ INCOME [Dollar Icon]
        β”œβ”€β”€ SAVINGS [Piggy Bank Icon]
        β”œβ”€β”€ INVESTMENTS [Graph Icon]
        └── EXPENSES
            β”œβ”€β”€ FIXED [Lock Icon]
            └── VARIABLE [Scale Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Team Structure",
        "prompt": """A handrawn colorful mind map diagram, organizational style, team hierarchy.
        TEAM
        β”œβ”€β”€ LEADERSHIP [Crown Icon]
        β”œβ”€β”€ MANAGERS [Briefcase Icon]
        β”œβ”€β”€ SPECIALISTS [Star Icon]
        └── SUPPORT
            β”œβ”€β”€ HR [Heart Icon]
            └── IT [Gear Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Learning Methods",
        "prompt": """A handrawn colorful mind map diagram, educational style, learning approaches.
        LEARNING
        β”œβ”€β”€ VISUAL [Eye Icon]
        β”œβ”€β”€ AUDITORY [Ear Icon]
        β”œβ”€β”€ READING [Book Icon]
        └── KINESTHETIC
            β”œβ”€β”€ PRACTICE [Hand Icon]
            └── EXPERIENCE [Star Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Content Creation",
        "prompt": """A handrawn colorful mind map diagram, creative style, content types.
        CONTENT
        β”œβ”€β”€ TEXT [Document Icon]
        β”œβ”€β”€ IMAGES [Camera Icon]
        β”œβ”€β”€ VIDEO [Play Icon]
        └── AUDIO
            β”œβ”€β”€ PODCAST [Microphone Icon]
            └── MUSIC [Note Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Risk Management",
        "prompt": """A handrawn colorful mind map diagram, analytical style, risk assessment.
        RISK
        β”œβ”€β”€ IDENTIFY [Eye Icon]
        β”œβ”€β”€ ANALYZE [Graph Icon]
        β”œβ”€β”€ MITIGATE [Shield Icon]
        └── MONITOR
            β”œβ”€β”€ TRACK [Chart Icon]
            └── REPORT [Document Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Quality Assurance",
        "prompt": """A handrawn colorful mind map diagram, technical style, quality control.
        QUALITY
        β”œβ”€β”€ STANDARDS [Checkmark Icon]
        β”œβ”€β”€ TESTING [Magnifier Icon]
        β”œβ”€β”€ INSPECTION [Eye Icon]
        └── IMPROVEMENT
            β”œβ”€β”€ FEEDBACK [Chat Icon]
            └── ACTION [Gear Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Communication Channels",
        "prompt": """A handrawn colorful mind map diagram, network style, communication methods.
        COMMUNICATION
        β”œβ”€β”€ EMAIL [Envelope Icon]
        β”œβ”€β”€ CHAT [Message Icon]
        β”œβ”€β”€ PHONE [Phone Icon]
        └── MEETINGS
            β”œβ”€β”€ VIRTUAL [Screen Icon]
            └── IN-PERSON [Group Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Career Development",
        "prompt": """A handrawn colorful mind map diagram, professional style, career growth.
        CAREER
        β”œβ”€β”€ SKILLS [Tools Icon]
        β”œβ”€β”€ EXPERIENCE [Clock Icon]
        β”œβ”€β”€ NETWORK [Connect Icon]
        └── GOALS
            β”œβ”€β”€ SHORT [Flag Icon]
            └── LONG [Mountain Icon]""",
        "width": 1024,
        "height": 1024
    },
    {
        "title": "Problem Solving",
        "prompt": """A handrawn colorful mind map diagram, analytical style, solution process.
        PROBLEM
        β”œβ”€β”€ IDENTIFY [Eye Icon]
        β”œβ”€β”€ ANALYZE [Brain Icon]
        β”œβ”€β”€ SOLVE [Key Icon]
        └── VERIFY
            β”œβ”€β”€ TEST [Checkbox Icon]
            └── REVIEW [Magnifier Icon]""",
        "width": 1024,
        "height": 1024
    }
]








class DiagramCache:
    def __init__(self, cache_dir: Path):
        self.cache_dir = cache_dir
        self.cache_dir.mkdir(exist_ok=True)
        self._load_cache()
    
    def _load_cache(self):
        """Load existing cache entries"""
        self.cache_index = {}
        if (self.cache_dir / "cache_index.json").exists():
            with open(self.cache_dir / "cache_index.json", "r") as f:
                self.cache_index = json.load(f)
    
    def _save_cache_index(self):
        """Save cache index to disk"""
        with open(self.cache_dir / "cache_index.json", "w") as f:
            json.dump(self.cache_index, f)
    
    def _get_cache_key(self, params: Dict[str, Any]) -> str:
        """Generate cache key from parameters"""
        param_str = json.dumps(params, sort_keys=True)
        return hashlib.md5(param_str.encode()).hexdigest()
    
    def get(self, params: Dict[str, Any]) -> Path:
        """Get cached result if exists"""
        cache_key = self._get_cache_key(params)
        cache_info = self.cache_index.get(cache_key)
        if cache_info:
            cache_path = self.cache_dir / cache_info["filename"]
            if cache_path.exists():
                return cache_path
        return None
    
    def put(self, params: Dict[str, Any], result_path: Path):
        """Store result in cache"""
        cache_key = self._get_cache_key(params)
        filename = f"{cache_key}{result_path.suffix}"
        cache_path = self.cache_dir / filename
        
        # Copy result to cache
        with open(result_path, "rb") as src, open(cache_path, "wb") as dst:
            dst.write(src.read())
        
        # Update index
        self.cache_index[cache_key] = {
            "filename": filename,
            "timestamp": time.time(),
            "params": params
        }
        self._save_cache_index()


# Initialize cache
diagram_cache = DiagramCache(CACHE_DIR)

@st.cache_data
def generate_cached_example(example_id: str) -> str:
    """Generate and cache example diagram"""
    example = CACHED_EXAMPLES[example_id]
    client = Client("black-forest-labs/FLUX.1-schnell")
    
    # Check cache first
    cache_path = diagram_cache.get(example)
    if cache_path:
        with open(cache_path, "rb") as f:
            return base64.b64encode(f.read()).decode()
    
    # Generate new image
    result = client.predict(
        prompt=example["prompt"],
        seed=example["seed"],
        randomize_seed=False,
        width=example["width"],
        height=example["height"],
        num_inference_steps=4,
        api_name="/infer"
    )
    
    # Cache the result
    diagram_cache.put(example, Path(result))
    
    with open(result, "rb") as f:
        return base64.b64encode(f.read()).decode()

def generate_diagram(prompt: str, width: int, height: int, seed: int = None) -> str:
    """Generate a new diagram"""
    client = Client("black-forest-labs/FLUX.1-schnell")
    params = {
        "prompt": prompt,
        "seed": seed if seed else 1872187377,
        "width": width,
        "height": height
    }
    
    # Check cache first
    cache_path = diagram_cache.get(params)
    if cache_path:
        with open(cache_path, "rb") as f:
            return base64.b64encode(f.read()).decode()
    
    # Generate new image
    try:
        result = client.predict(
            prompt=prompt,
            seed=params["seed"],
            randomize_seed=False,
            width=width,
            height=height,
            num_inference_steps=4,
            api_name="/infer"
        )
        
        # Cache the result
        diagram_cache.put(params, Path(result))
        
        with open(result, "rb") as f:
            return base64.b64encode(f.read()).decode()
    except Exception as e:
        st.error(f"Error generating diagram: {str(e)}")
        return None


def main():
    st.set_page_config(page_title="FLUX Diagram Generator", layout="wide", initial_sidebar_state="expanded")
    
    if "initialized" not in st.session_state:
        st.session_state.initialized = True
        st.session_state.generated_images = {}

    st.title("🎨 FLUX Diagram Generator")
    st.markdown("Generate beautiful hand-drawn style diagrams using FLUX AI")

    # Initialize client
    client = Client("black-forest-labs/FLUX.1-schnell", hf_token=HF_TOKEN)

    # Sidebar with examples
    st.sidebar.title("πŸ“š Example Templates")
    selected_example = st.sidebar.selectbox(
        "Choose a template",
        options=range(len(DIAGRAM_EXAMPLES)),
        format_func=lambda x: DIAGRAM_EXAMPLES[x]["title"]
    )

    # Main content
    col1, col2 = st.columns([2, 1])

    with col1:
        example = DIAGRAM_EXAMPLES[selected_example]
        prompt = st.text_area("Diagram Prompt", value=example["prompt"], height=200)
        
        with st.expander("Advanced Configuration"):
            width = st.number_input("Width", min_value=512, max_value=2048, value=1024, step=128)
            height = st.number_input("Height", min_value=512, max_value=2048, value=1024, step=128)

        if st.button("🎨 Generate Diagram"):
            try:
                with st.spinner("Generating diagram..."):
                    result = client.predict(
                        prompt,
                        1872187377,  # seed
                        False,       # randomize_seed
                        width,
                        height,
                        4,          # num_inference_steps
                        api_name="/infer"
                    )
                    st.session_state.generated_images[prompt] = result
                    st.image(result, caption="Generated Diagram", use_column_width=True)
            except Exception as e:
                st.error(f"Error generating diagram: {str(e)}")

    with col2:
        st.subheader("Tips for Better Results")
        st.markdown("""
        - Use clear hierarchical structures
        - Include icon descriptions in brackets
        - Keep text concise and meaningful
        - Use consistent formatting
        """)

        st.subheader("Template Structure")
        st.code("""
        MAIN TOPIC
        β”œβ”€β”€ SUBTOPIC 1 [Icon]
        β”œβ”€β”€ SUBTOPIC 2 [Icon]
        └── SUBTOPIC 3
            β”œβ”€β”€ DETAIL 1 [Icon]
            └── DETAIL 2 [Icon]
        """)

if __name__ == "__main__":
    main()