yukee1992 commited on
Commit
d661abf
Β·
verified Β·
1 Parent(s): 83dc960

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -37
app.py CHANGED
@@ -18,6 +18,7 @@ import threading
18
  import uuid
19
  import hashlib
20
  from enum import Enum
 
21
 
22
  # External OCI API URL
23
  OCI_API_BASE_URL = "https://yukee1992-oci-story-book.hf.space"
@@ -202,7 +203,6 @@ def enhance_prompt(prompt, style="childrens_book"):
202
  ]
203
 
204
  # Add 2-3 random quality boosters
205
- import random
206
  boosters = random.sample(quality_boosters, 2)
207
  enhanced += ", " + ", ".join(boosters)
208
 
@@ -523,76 +523,166 @@ async def list_jobs():
523
  }
524
  }
525
 
526
-
527
- # GRADIO INTERFACE (Optional - for manual testing)
528
- def create_gradio_interface():
529
- """Create Gradio interface for manual testing"""
530
- with gr.Blocks(title="High-Quality Storybook Generator", theme="soft") as demo:
531
- gr.Markdown("# 🎨 High-Quality Storybook Generator")
532
- gr.Markdown("Generate **studio-quality** storybook images with professional results")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
533
 
534
  with gr.Row():
535
  with gr.Column(scale=1):
536
- gr.Markdown("### 🎯 Quality Settings")
537
 
538
- model_choice = gr.Dropdown(
539
  label="AI Model",
540
  choices=list(MODEL_CHOICES.keys()),
541
  value="dreamshaper-8",
542
- info="Choose the best model for your style"
543
  )
544
 
545
- style_choice = gr.Dropdown(
546
  label="Art Style",
547
  choices=["childrens_book", "realistic", "fantasy", "anime"],
548
  value="childrens_book",
549
  info="Select the artistic style"
550
  )
551
 
552
- story_title = gr.Textbox(
553
- label="Story Title",
554
- placeholder="Enter your story title..."
555
- )
556
-
557
- scene_input = gr.Textbox(
558
- label="Scene Description",
559
- placeholder="Describe your scene in detail...",
560
  lines=3
561
  )
562
 
563
- generate_btn = gr.Button("✨ Generate Premium Image", variant="primary")
 
 
 
 
 
 
 
564
 
565
  with gr.Column(scale=2):
566
- image_output = gr.Image(label="Generated Image", height=500, show_download_button=True)
567
- status_output = gr.Textbox(label="Status", interactive=False, lines=3)
 
 
 
 
 
 
 
 
 
 
568
 
569
- def generate_single_image(story_title, scene, model, style):
570
- """Generate a single high-quality image for testing"""
571
- try:
572
- prompt, negative_prompt = enhance_prompt(scene, style)
573
- image = generate_high_quality_image(prompt, model, style, negative_prompt)
574
- return image, f"βœ… High-quality image generated for: {story_title}"
575
- except Exception as e:
576
- return None, f"❌ Error: {str(e)}"
 
577
 
 
578
  generate_btn.click(
579
- fn=generate_single_image,
580
- inputs=[story_title, scene_input, model_choice, style_choice],
581
  outputs=[image_output, status_output]
582
  )
583
 
584
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
585
 
586
  # For Hugging Face Spaces deployment
587
  def get_app():
588
  return app
589
 
 
590
  if __name__ == "__main__":
591
  import uvicorn
592
- print("πŸš€ Starting High-Quality Storybook Generator API...")
593
  print("🎨 Available models:")
594
  for model in MODEL_CHOICES:
595
  print(f" - {model}")
 
 
596
 
597
- # Start both FastAPI and Gradio (if needed)
598
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
18
  import uuid
19
  import hashlib
20
  from enum import Enum
21
+ import random
22
 
23
  # External OCI API URL
24
  OCI_API_BASE_URL = "https://yukee1992-oci-story-book.hf.space"
 
203
  ]
204
 
205
  # Add 2-3 random quality boosters
 
206
  boosters = random.sample(quality_boosters, 2)
207
  enhanced += ", " + ", ".join(boosters)
208
 
 
523
  }
524
  }
525
 
526
+ # SIMPLIFIED GRADIO INTERFACE FOR TESTING
527
+ def create_test_interface():
528
+ """Create a simple Gradio interface for testing image generation"""
529
+
530
+ def generate_test_image(prompt, model_choice, style_choice):
531
+ """Generate a single image for testing"""
532
+ try:
533
+ if not prompt.strip():
534
+ return None, "❌ Please enter a prompt"
535
+
536
+ print(f"🎨 Generating test image with prompt: {prompt}")
537
+
538
+ # Enhance the prompt
539
+ enhanced_prompt, negative_prompt = enhance_prompt(prompt, style_choice)
540
+
541
+ # Generate the image
542
+ image = generate_high_quality_image(
543
+ enhanced_prompt,
544
+ model_choice,
545
+ style_choice,
546
+ negative_prompt
547
+ )
548
+
549
+ # Create a simple save (optional)
550
+ try:
551
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
552
+ safe_prompt = "".join(c for c in prompt[:20] if c.isalnum() or c in (' ', '-', '_')).rstrip()
553
+ filename = f"test_{safe_prompt}_{timestamp}.png"
554
+ image.save(f"/tmp/{filename}")
555
+ print(f"πŸ’Ύ Test image saved as: {filename}")
556
+ except Exception as e:
557
+ print(f"⚠️ Could not save test image: {e}")
558
+
559
+ status_msg = f"βœ… Success! Generated: {prompt}\n\nEnhanced prompt: {enhanced_prompt}"
560
+ return image, status_msg
561
+
562
+ except Exception as e:
563
+ error_msg = f"❌ Generation failed: {str(e)}"
564
+ print(error_msg)
565
+ return None, error_msg
566
+
567
+ # Create the interface
568
+ with gr.Blocks(title="High-Quality Image Generator", theme="soft") as demo:
569
+ gr.Markdown("# 🎨 High-Quality Image Generator")
570
+ gr.Markdown("Test your prompts with **studio-quality** image generation")
571
 
572
  with gr.Row():
573
  with gr.Column(scale=1):
574
+ gr.Markdown("### βš™οΈ Settings")
575
 
576
+ model_dropdown = gr.Dropdown(
577
  label="AI Model",
578
  choices=list(MODEL_CHOICES.keys()),
579
  value="dreamshaper-8",
580
+ info="Choose the model for generation"
581
  )
582
 
583
+ style_dropdown = gr.Dropdown(
584
  label="Art Style",
585
  choices=["childrens_book", "realistic", "fantasy", "anime"],
586
  value="childrens_book",
587
  info="Select the artistic style"
588
  )
589
 
590
+ prompt_input = gr.Textbox(
591
+ label="Prompt",
592
+ placeholder="Describe what you want to generate...\nExample: A friendly dragon reading a book under a magical tree",
 
 
 
 
 
593
  lines=3
594
  )
595
 
596
+ generate_btn = gr.Button("✨ Generate Image", variant="primary", size="lg")
597
+
598
+ gr.Markdown("### πŸ’‘ Tips")
599
+ gr.Markdown("""
600
+ - Be descriptive with colors, emotions, settings
601
+ - Example: **"A cute baby dragon with green scales reading a giant book under a glowing mushroom"**
602
+ - Avoid single words: use **"friendly cartoon dragon"** instead of just **"dragon"**
603
+ """)
604
 
605
  with gr.Column(scale=2):
606
+ image_output = gr.Image(
607
+ label="Generated Image",
608
+ height=500,
609
+ show_download_button=True,
610
+ show_share_button=True
611
+ )
612
+ status_output = gr.Textbox(
613
+ label="Generation Status",
614
+ interactive=False,
615
+ lines=4,
616
+ show_copy_button=True
617
+ )
618
 
619
+ # Examples section
620
+ with gr.Accordion("🎯 Example Prompts", open=False):
621
+ gr.Markdown("""
622
+ **Try these examples:**
623
+ - "A friendly dragon reading a giant book under a magical tree with glowing fairies"
624
+ - "Cute kitten playing with yarn ball in a sunny living room"
625
+ - "Space astronaut exploring a colorful alien planet with strange creatures"
626
+ - "Magical castle in the clouds with rainbows and flying unicorns"
627
+ """)
628
 
629
+ # Connect the button
630
  generate_btn.click(
631
+ fn=generate_test_image,
632
+ inputs=[prompt_input, model_dropdown, style_dropdown],
633
  outputs=[image_output, status_output]
634
  )
635
 
636
+ # Quick test buttons
637
+ gr.Markdown("### πŸš€ Quick Test Prompts")
638
+ with gr.Row():
639
+ quick_btn1 = gr.Button("πŸ‰ Dragon Example", size="sm")
640
+ quick_btn2 = gr.Button("🐱 Kitten Example", size="sm")
641
+ quick_btn3 = gr.Button("πŸš€ Space Example", size="sm")
642
+
643
+ def set_quick_prompt1():
644
+ return "A friendly dragon reading a giant book under a magical tree with glowing fairies"
645
+
646
+ def set_quick_prompt2():
647
+ return "Cute kitten playing with yarn ball in a sunny living room with sunbeams"
648
+
649
+ def set_quick_prompt3():
650
+ return "Space astronaut exploring a colorful alien planet with strange glowing plants"
651
+
652
+ quick_btn1.click(fn=set_quick_prompt1, outputs=prompt_input)
653
+ quick_btn2.click(fn=set_quick_prompt2, outputs=prompt_input)
654
+ quick_btn3.click(fn=set_quick_prompt3, outputs=prompt_input)
655
+
656
+ return demo
657
+
658
+ # Create the Gradio app
659
+ gradio_app = create_test_interface()
660
+
661
+ # Mount Gradio interface to FastAPI
662
+ @app.get("/")
663
+ async def root():
664
+ return {"message": "Storybook Generator API is running! Visit /gradio for the testing interface."}
665
+
666
+ @app.get("/gradio")
667
+ async def gradio_redirect():
668
+ """Redirect to Gradio interface"""
669
+ import urllib.parse
670
+ gradio_url = "http://localhost:7860" if __name__ == "__main__" else "/gradio"
671
+ return {"message": "Visit the Gradio interface at the main URL"}
672
 
673
  # For Hugging Face Spaces deployment
674
  def get_app():
675
  return app
676
 
677
+ # Launch both FastAPI and Gradio
678
  if __name__ == "__main__":
679
  import uvicorn
680
+ print("πŸš€ Starting High-Quality Storybook Generator...")
681
  print("🎨 Available models:")
682
  for model in MODEL_CHOICES:
683
  print(f" - {model}")
684
+ print("🌐 Web interface available at: http://localhost:7860")
685
+ print("πŸ”Œ API endpoints available at: http://localhost:7860/api/")
686
 
687
+ # Launch Gradio interface
688
+ gradio_app.launch(server_name="0.0.0.0", server_port=7860, share=False)