Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229import randomimport osimport uuidfrom datetime import datetimeimport gradio as grimport numpy as npimport spacesimport torchfrom diffusers import DiffusionPipelinefrom PIL import Image# Create permanent storage directorySAVE_DIR = "saved_images" # Gradio will handle the persistenceif not os.path.exists(SAVE_DIR):os.makedirs(SAVE_DIR, exist_ok=True)device = "cuda" if torch.cuda.is_available() else "cpu"repo_id = "black-forest-labs/FLUX.1-dev"adapter_id = "openfree/korea-president-yoon"pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16)pipeline.load_lora_weights(adapter_id)pipeline = pipeline.to(device)MAX_SEED = np.iinfo(np.int32).maxMAX_IMAGE_SIZE = 1024def save_generated_image(image, prompt):# Generate unique filename with timestamptimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]filename = f"{timestamp}_{unique_id}.png"filepath = os.path.join(SAVE_DIR, filename)# Save the imageimage.save(filepath)# Save metadatametadata_file = os.path.join(SAVE_DIR, "metadata.txt")with open(metadata_file, "a", encoding="utf-8") as f:f.write(f"{filename}|{prompt}|{timestamp}\n")return filepathdef load_generated_images():if not os.path.exists(SAVE_DIR):return []# Load all images from the directoryimage_files = [os.path.join(SAVE_DIR, f) for f in os.listdir(SAVE_DIR)if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))]# Sort by creation time (newest first)image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)return image_filesdef load_predefined_images():# Return empty list since we're not using predefined imagesreturn []@spaces.GPU(duration=120)def inference(prompt: str,seed: int,randomize_seed: bool,width: int,height: int,guidance_scale: float,num_inference_steps: int,lora_scale: float,progress: gr.Progress = gr.Progress(track_tqdm=True),):if randomize_seed:seed = random.randint(0, MAX_SEED)generator = torch.Generator(device=device).manual_seed(seed)image = pipeline(prompt=prompt,guidance_scale=guidance_scale,num_inference_steps=num_inference_steps,width=width,height=height,generator=generator,joint_attention_kwargs={"scale": lora_scale},).images[0]# Save the generated imagefilepath = save_generated_image(image, prompt)# Return the image, seed, and updated galleryreturn image, seed, load_generated_images()examples = ["A man playing fetch with a golden retriever in a sunny park. He wears casual weekend clothes and throws a red frisbee with joy. The dog leaps gracefully through the air, tail wagging with excitement. Warm afternoon sunlight filters through the trees, creating a peaceful scene of companionship. [president yoon]","A soldier standing at attention in full military gear, holding a standard-issue rifle. His uniform is crisp and properly adorned with medals. Behind him, other soldiers march in formation during a military parade. The scene conveys discipline and duty. [president yoon]","A medieval knight in gleaming armor, holding an ornate sword and shield. He stands proudly in front of a majestic castle, his cape flowing in the wind. The shield bears intricate heraldic designs, and sunlight glints off his polished armor. [president yoon]","A charismatic political leader addressing a crowd from a podium. He wears a well-fitted suit and gestures confidently while speaking. The audience fills a large plaza, holding supportive banners and signs. News cameras capture the moment as he delivers his speech. [president yoon]","A man enjoying a peaceful morning at home, reading a newspaper at his breakfast table. He wears comfortable home clothes and sips coffee from a favorite mug. Sunlight streams through the kitchen window, and a house plant adds a touch of nature to the cozy domestic scene. [president yoon]","A businessman walking confidently through a modern office building. He carries a leather briefcase and wears a tailored navy suit. Floor-to-ceiling windows reveal a cityscape behind him, and his expression shows determination and purpose. [president yoon]"]css = """footer {visibility: hidden;}"""with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, analytics_enabled=False) as demo:gr.HTML('<div class="title"> President Yoon in KOREA </div>')gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fopenfree-korea-president-yoon.hf.space"><img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fopenfree-korea-president-yoon.hf.space&countColor=%23263759" /></a>""")with gr.Tabs() as tabs:with gr.Tab("Generation"):with gr.Column(elem_id="col-container"):with gr.Row():prompt = gr.Text(label="Prompt",show_label=False,max_lines=1,placeholder="Enter your prompt",container=False,)run_button = gr.Button("Run", scale=0)result = gr.Image(label="Result", show_label=False)with gr.Accordion("Advanced Settings", open=False):seed = gr.Slider(label="Seed",minimum=0,maximum=MAX_SEED,step=1,value=42,)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)with gr.Row():width = gr.Slider(label="Width",minimum=256,maximum=MAX_IMAGE_SIZE,step=32,value=1024,)height = gr.Slider(label="Height",minimum=256,maximum=MAX_IMAGE_SIZE,step=32,value=768,)with gr.Row():guidance_scale = gr.Slider(label="Guidance scale",minimum=0.0,maximum=10.0,step=0.1,value=3.5,)num_inference_steps = gr.Slider(label="Number of inference steps",minimum=1,maximum=50,step=1,value=30,)lora_scale = gr.Slider(label="LoRA scale",minimum=0.0,maximum=1.0,step=0.1,value=1.0,)gr.Examples(examples=examples,inputs=[prompt],outputs=[result, seed],)with gr.Tab("Gallery"):gallery_header = gr.Markdown("### Generated Images Gallery")generated_gallery = gr.Gallery(label="Generated Images",columns=6,show_label=False,value=load_generated_images(),elem_id="generated_gallery",height="auto")refresh_btn = gr.Button("π Refresh Gallery")# Event handlersdef refresh_gallery():return load_generated_images()refresh_btn.click(fn=refresh_gallery,inputs=None,outputs=generated_gallery,)gr.on(triggers=[run_button.click, prompt.submit],fn=inference,inputs=[prompt,seed,randomize_seed,width,height,guidance_scale,num_inference_steps,lora_scale,],outputs=[result, seed, generated_gallery],)demo.queue()demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283# app.pyimport osimport base64import streamlit as stfrom gradio_client import Clientfrom dotenv import load_dotenvfrom pathlib import Pathimport jsonimport hashlibimport timefrom typing import Dict, Any# Load environment variablesload_dotenv()HF_TOKEN = os.getenv("HF_TOKEN")# Cache directory setupCACHE_DIR = Path("./cache")CACHE_DIR.mkdir(exist_ok=True)# Cached example diagramsCACHED_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 textsLITERACY/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"}}# Example diagrams for various use casesDIAGRAM_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}]# Add 15 more examplesADDITIONAL_EXAMPLES = [{"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}# ... (λλ¨Έμ§ μμ λ€)]class DiagramCache:def __init__(self, cache_dir: Path):self.cache_dir = cache_dirself.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_pathreturn Nonedef 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 cachewith open(result_path, "rb") as src, open(cache_path, "wb") as dst:dst.write(src.read())# Update indexself.cache_index[cache_key] = {"filename": filename,"timestamp": time.time(),"params": params}self._save_cache_index()# Initialize cachediagram_cache = DiagramCache(CACHE_DIR)@st.cache_datadef 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 firstcache_path = diagram_cache.get(example)if cache_path:with open(cache_path, "rb") as f:return base64.b64encode(f.read()).decode()# Generate new imageresult = 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 resultdiagram_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 firstcache_path = diagram_cache.get(params)if cache_path:with open(cache_path, "rb") as f:return base64.b64encode(f.read()).decode()# Generate new imagetry:result = client.predict(prompt=prompt,seed=params["seed"],randomize_seed=False,width=width,height=height,num_inference_steps=4,api_name="/infer")# Cache the resultdiagram_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 Nonedef main():st.set_page_config(page_title="FLUX Diagram Generator", layout="wide")st.title("π¨ FLUX Diagram Generator")st.markdown("Generate beautiful hand-drawn style diagrams using FLUX AI")# Sidebar for examplesst.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 areacol1, col2 = st.columns([2, 1])with col1:# Input areaprompt = st.text_area("Diagram Prompt",value=DIAGRAM_EXAMPLES[selected_example]["prompt"],height=200)# Configurationwith 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)seed = st.number_input("Seed (optional)", value=None, step=1)if st.button("π¨ Generate Diagram"):with st.spinner("Generating your diagram..."):result = generate_diagram(prompt, width, height, seed)if result:st.image(result, caption="Generated Diagram", use_column_width=True)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()
app.py+263-209