Spaces:
Sleeping
Sleeping
File size: 35,203 Bytes
8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 9841228 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 65971fd 8ae87a8 9841228 8ae87a8 |
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 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 |
import gradio as gr
from supertonic import TTS
from transformers import pipeline
import tempfile
import os
from PIL import Image
import numpy as np
# Initialize the image-to-text pipeline
image_to_text = pipeline("image-to-text")
# Initialize text generation pipeline for story creation
text_generation = pipeline("text-generation", model="gpt2")
# Initialize Hugging Face image-to-text model for advanced story generation
try:
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
image_to_story_model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
image_feature_extractor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
image_to_story_tokenizer = AutoTokenizer.from_pretrained("gpt2")
except:
image_to_story_model = None
image_feature_extractor = None
image_to_story_tokenizer = None
# Initialize the TTS model
tts = TTS(auto_download=True)
# Initialize emotion detection pipeline
try:
emotion_detection = pipeline("image-classification", model="nateraw/vit-base-beans")
except:
emotion_detection = None
# Available voice styles (common Supertonic voices)
VOICE_OPTIONS = [
("M5 - Male Voice (Default)", "M5"),
("M1 - Male Voice 1", "M1"),
("M2 - Male Voice 2", "M2"),
("M3 - Male Voice 3", "M3"),
("M4 - Male Voice 4", "M4"),
("F1 - Female Voice 1", "F1"),
("F2 - Female Voice 2", "F2"),
("F3 - Female Voice 3", "F3"),
("F4 - Female Voice 4", "F4"),
("F5 - Female Voice 5", "F5"),
]
def image_to_voice(image, voice_selection):
"""
Convert an image to text, then text to speech.
Args:
image: Input image (PIL Image or numpy array)
voice_selection: Selected voice style from dropdown (e.g., "M5 - Male Voice (Default)")
Returns:
Path to the generated audio file and extracted text
"""
if image is None:
return None, "Please upload an image to get started."
try:
# Extract voice name from selection (e.g., "M5 - Male Voice (Default)" -> "M5")
voice_name = None
for opt_label, opt_value in VOICE_OPTIONS:
if opt_label == voice_selection:
voice_name = opt_value
break
if voice_name is None:
# Fallback: try to extract from the selection if format is unexpected
voice_name = voice_selection.split(" - ")[0] if " - " in voice_selection else voice_selection
# Convert image to text
result = image_to_text(image)
generated_text = result[0]['generated_text']
# Get the selected voice style
style = tts.get_voice_style(voice_name=voice_name)
# Convert text to speech
wav, duration = tts.synthesize(generated_text, voice_style=style)
# Save to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
tts.save_audio(wav, temp_file.name)
return temp_file.name, generated_text
except Exception as e:
return None, f"โ Error: {str(e)}"
def analyze_mood_from_image(image):
"""
Analyze mood/emotions detected in an image and create a mood chart.
Args:
image: Input image (PIL Image or numpy array)
Returns:
Chart data and mood analysis text
"""
if image is None:
return "Please upload an image.", {}
try:
# Simple mood detection based on color analysis
img_array = np.array(image)
# Calculate average colors
avg_brightness = np.mean(img_array)
avg_red = np.mean(img_array[:, :, 0]) if img_array.shape[2] > 0 else 0
avg_green = np.mean(img_array[:, :, 1]) if img_array.shape[2] > 1 else 0
avg_blue = np.mean(img_array[:, :, 2]) if img_array.shape[2] > 2 else 0
# Create mood mapping based on color analysis
mood_scores = {
"Happy": min(100, int((avg_brightness / 255 * 60) + (avg_yellow := (avg_red + avg_green) / 2 - avg_blue) / 2.55 * 40)),
"Calm": min(100, int((avg_blue / 255 * 50) + (avg_green / 255 * 50))),
"Energetic": min(100, int(avg_red / 255 * 100)),
"Peaceful": min(100, int((255 - avg_brightness) / 255 * 70 + avg_blue / 255 * 30)),
}
# Normalize scores
total = sum(mood_scores.values())
mood_scores = {k: int((v / total * 100)) for k, v in mood_scores.items()} if total > 0 else mood_scores
mood_text = f"""
**Mood Analysis Results:**
- ๐ Happy: {mood_scores.get('Happy', 0)}%
- ๐ Calm: {mood_scores.get('Calm', 0)}%
- โก Energetic: {mood_scores.get('Energetic', 0)}%
- ๐ง Peaceful: {mood_scores.get('Peaceful', 0)}%
**Interpretation:** Based on color analysis, this image conveys a {max(mood_scores, key=mood_scores.get)} mood.
"""
return mood_text, mood_scores
except Exception as e:
return f"โ Error analyzing mood: {str(e)}", {}
def ai_story_generation(image, story_theme):
"""
Generate a creative story based on the image content and selected theme.
Args:
image: Input image (PIL Image or numpy array)
story_theme: Selected theme for the story
Returns:
Generated story text
"""
if image is None:
return "Please upload an image to generate a story."
try:
# Extract text from image first
result = image_to_text(image)
image_description = result[0]['generated_text']
# Create a prompt for story generation
prompt = f"""Based on an image showing: {image_description}
Theme: {story_theme}
Generate a creative and engaging short story (150-200 words) incorporating elements from the image:"""
# Generate story using text generation pipeline
story = text_generation(prompt, max_length=250, num_return_sequences=1)
generated_story = story[0]['generated_text']
return generated_story
except Exception as e:
return f"โ Error generating story: {str(e)}"
def huggingface_picture_to_story(image):
"""
Transform a picture into a story using Hugging Face image-to-text model.
Uses the specialized vit-gpt2-image-captioning model.
Args:
image: Input image (PIL Image or numpy array)
Returns:
Generated story based on image
"""
if image is None:
return "Please upload an image to generate a story."
try:
if image_to_story_model is None or image_feature_extractor is None:
return "Hugging Face story model not available. Using alternative method..."
# Prepare image
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
# Extract features from image
pixel_values = image_feature_extractor(images=image, return_tensors="pt").pixel_values
# Generate story
output_ids = image_to_story_model.generate(pixel_values, max_length=100)
# Decode the generated text
story = image_to_story_tokenizer.batch_decode(output_ids, skip_special_tokens=True)
generated_story = story[0].strip() if story else "No story generated"
# Expand the basic caption into a more complete story
expanded_story = f"""
**AI-Generated Story from Image:**
{generated_story}
---
**Extended Story:**
In this captivating scene, {generated_story.lower()}. The image captures a moment of pure artistry and wonder,
where every detail tells a part of a larger narrative. As you observe the composition, your mind fills with possibilities
and untold stories waiting to be discovered. The interplay of light and shadow creates an atmosphere that invites
contemplation and imagination, transporting you to a world where reality meets fantasy.
"""
return expanded_story
except Exception as e:
return f"โ Error generating story: {str(e)}"
def ai_study_helper(image, study_type):
"""
Provide AI-powered study insights based on image content.
Args:
image: Input image (PIL Image or numpy array)
study_type: Type of study aid requested
Returns:
Study insights and recommendations
"""
if image is None:
return "Please upload an image for study assistance."
try:
# Extract text from image
result = image_to_text(image)
extracted_text = result[0]['generated_text']
study_insights = ""
if study_type == "Summary":
study_insights = f"""
**AI-Generated Summary:**
{extracted_text[:200]}...
**Key Points:**
- Content extracted from image: {extracted_text}
- Length: {len(extracted_text.split())} words
- Recommended study time: {max(5, len(extracted_text.split()) // 100)} minutes
"""
elif study_type == "Quiz Questions":
study_insights = f"""
**AI-Generated Study Questions:**
Based on the image content: "{extracted_text[:100]}..."
1. What are the main topics covered in the image?
2. Can you explain the concepts in your own words?
3. How would you apply this information?
4. What are the key takeaways?
5. What additional research would enhance your understanding?
"""
elif study_type == "Learning Tips":
study_insights = f"""
**Personalized Learning Tips:**
๐ Study Strategy:
- Break down the content: {extracted_text[:50]}...
- Use the Feynman Technique to explain concepts simply
- Create mind maps for visual learning
- Practice active recall with the quiz questions feature
- Review regularly (spaced repetition)
๐ฏ Focus Areas:
- Main concept: Extract and understand key terms
- Relationships: Connect ideas together
- Application: Practice with real-world examples
"""
else: # Note-Taking
study_insights = f"""
**AI-Generated Study Notes:**
**Original Content:**
{extracted_text}
**Simplified Notes:**
- Main idea: {extracted_text[:80]}...
- Key details: Analyze and list important points
- Examples: Look for practical applications
- Conclusion: What did you learn?
**Action Items:**
โ Review these notes daily
โ Create flashcards for key terms
โ Test yourself with quiz questions
"""
return study_insights
except Exception as e:
return f"โ Error generating study insights: {str(e)}"
def ai_study_helper_for_kids(image, learning_style):
"""
Provide AI-powered kid-friendly study assistance based on image content.
Uses simple language, fun facts, and gamified learning elements.
Args:
image: Input image (PIL Image or numpy array)
learning_style: Type of kid-friendly learning aid
Returns:
Kid-friendly study content with fun and engaging format
"""
if image is None:
return "Please upload an image for your learning adventure! ๐"
try:
# Extract text from image
result = image_to_text(image)
extracted_text = result[0]['generated_text']
study_content = ""
if learning_style == "Fun Summary":
study_content = f"""
โจ **FUN SUMMARY FOR KIDS!** โจ
๐ What We're Learning About:
{extracted_text}
๐ฏ Super Cool Points to Remember:
โญ The main idea is: {extracted_text[:60]}...
โญ This is important because it helps us understand cool stuff!
โญ You can find examples of this everywhere around you!
๐ก Fun Fact: Did you know? Learning by playing is the best way! ๐ฎ
โฑ๏ธ Perfect Study Time: 10-15 minutes is awesome! Then take a break! ๐
"""
elif learning_style == "Interactive Quiz":
study_content = f"""
๐ฎ **SUPER FUN QUIZ TIME!** ๐ฎ
Based on: {extracted_text[:80]}...
๐ Try to Answer These Fun Questions:
โ Question 1: What's the MAIN thing about this topic?
๐ญ Think about it... You got this! ๐ช
โ Question 2: Can you tell your friend about this in simple words?
๐ญ Teaching others is the BEST way to learn! ๐
โ Question 3: Where do you see this in real life?
๐ญ (Hint: Look around you!) ๐
โ Question 4: What's the coolest part of this?
๐ญ Everyone learns what's cool to THEM! ๐
๐ YOU'RE AMAZING FOR TRYING! ๐
"""
elif learning_style == "Memory Game":
words = extracted_text.split()[:5]
study_content = f"""
๐ง **MEMORY CHAMPION CHALLENGE!** ๐ง
Let's train your SUPER BRAIN! ๐ฏ
๐ Key Words to Remember:
{', '.join([f'โจ {word}' for word in words])}
๐ฎ MEMORY GAME RULES:
1๏ธโฃ Read the words above carefully (10 seconds)
2๏ธโฃ Close your eyes and think about them
3๏ธโฃ Can you remember them all? Try it!
4๏ธโฃ Repeat this game 3 times to be a MEMORY MASTER! ๐
๐ช YOUR BRAIN POWER IS INCREASING!
๐ Track your progress:
- Try 1: How many did you remember? ___/5
- Try 2: How many did you remember? ___/5
- Try 3: How many did you remember? ___/5
๐ AWESOME JOB! Your brain is SUPER POWERFUL! ๐
"""
else: # Learning Tips for Kids
study_content = f"""
๐ **SUPER COOL LEARNING TIPS FOR YOU!** ๐
Topic: {extracted_text[:100]}...
๐ฏ AWESOME STUDY TRICKS:
๐จ Make It Colorful!
- Use different colored pens or pencils
- Draw pictures to remember things
- Make it FUN and PRETTY! ๐๏ธ
๐ต Use Music & Rhythm!
- Make up a song about what you're learning
- Sing it while you study
- Dance while learning = SUPER FUN! ๐ถ
๐ฌ Act It Out!
- Use hand movements to remember ideas
- Tell your friends like you're a teacher
- Pretend you're explaining to an alien! ๐ฝ
๐ Move Your Body!
- Study for 10 minutes, then play for 5 minutes
- Jump, stretch, or dance between lessons
- Exercise helps your brain grow BIGGER & STRONGER! ๐ช
๐ฅ Study with Friends!
- Teaching each other is the BEST way to learn
- Play learning games together
- Make it a FUN GROUP ACTIVITY! ๐
๐ YOU'RE A LEARNING SUPERSTAR! โญ
"""
return study_content
except Exception as e:
return f"๐ Oops! Something went wrong. Let's try again! Error: {str(e)}"
# Custom CSS for professional styling
custom_css = """
.gradio-container {
font-family: 'Inter', 'Segoe UI', system-ui, sans-serif !important;
}
.header {
text-align: center;
padding: 2rem 1rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 12px;
margin-bottom: 2rem;
color: white;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.header h1 {
margin: 0;
font-size: 2.5rem;
font-weight: 700;
letter-spacing: -0.02em;
}
.header p {
margin: 0.5rem 0 0 0;
opacity: 0.95;
font-size: 1.1rem;
}
.feature-box {
background: #f8f9fa;
border-radius: 10px;
padding: 1.5rem;
margin: 1rem 0;
border-left: 4px solid #667eea;
}
.feature-box h3 {
margin-top: 0;
color: #333;
font-size: 1.1rem;
}
.main-content {
max-width: 1200px;
margin: 0 auto;
}
.upload-section {
background: white;
border-radius: 12px;
padding: 2rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
margin-bottom: 1.5rem;
}
.output-section {
background: white;
border-radius: 12px;
padding: 2rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.generate-btn {
width: 100%;
padding: 1rem !important;
font-size: 1.1rem !important;
font-weight: 600 !important;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
border: none !important;
border-radius: 8px !important;
transition: transform 0.2s, box-shadow 0.2s !important;
}
.generate-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4) !important;
}
.footer {
text-align: center;
padding: 2rem 1rem;
margin-top: 3rem;
color: #666;
font-size: 0.9rem;
}
.section-title {
margin-top: 1rem;
margin-bottom: 1rem;
color: #333;
font-weight: 600;
}
select, .gr-dropdown {
border-radius: 8px !important;
border: 2px solid #e0e0e0 !important;
padding: 0.75rem !important;
font-size: 1rem !important;
transition: border-color 0.2s !important;
}
select:focus, .gr-dropdown:focus {
border-color: #667eea !important;
outline: none !important;
}
"""
# Create Gradio interface
with gr.Blocks(title="AI Multimedia Studio", theme=gr.themes.Soft(), css=custom_css) as demo:
# Header Section
gr.HTML("""
<div class="header">
<h1>๐จ AI Multimedia Studio</h1>
<p>Transform images with AI-powered technology: voice, stories, mood analysis & study tools</p>
</div>
""")
# Main Content Container
with gr.Column(elem_classes="main-content"):
# Create tabs for different features
with gr.Tabs():
# ===== TAB 1: Image to Voice =====
with gr.TabItem("๐๏ธ Image to Voice"):
# Instructions Section
with gr.Row():
with gr.Column(scale=1):
gr.HTML("""
<div class="feature-box">
<h3>๐ท Step 1: Upload Image</h3>
<p>Upload any image containing text. Our AI will extract it automatically.</p>
</div>
""")
with gr.Column(scale=1):
gr.HTML("""
<div class="feature-box">
<h3>๐ค Step 2: AI Processing</h3>
<p>Advanced vision-language models analyze and extract text from your image.</p>
</div>
""")
with gr.Column(scale=1):
gr.HTML("""
<div class="feature-box">
<h3>๐ Step 3: Audio Generation</h3>
<p>Text is converted to natural-sounding speech using Supertonic TTS.</p>
</div>
""")
# Main Workflow Section
with gr.Row():
# Left Column - Input
with gr.Column(scale=1, elem_classes="upload-section"):
gr.Markdown("### ๐ค Upload Your Image", elem_classes="section-title")
image_input = gr.Image(
label="",
type="pil",
height=350,
show_label=False
)
gr.Markdown("### ๐๏ธ Voice Settings", elem_classes="section-title")
voice_dropdown = gr.Dropdown(
choices=[opt[0] for opt in VOICE_OPTIONS],
label="Select Voice Style",
value="M5 - Male Voice (Default)",
info="Choose a voice style for the generated audio"
)
generate_btn = gr.Button(
"โจ Generate Audio",
variant="primary",
elem_classes="generate-btn",
size="lg"
)
# Right Column - Output
with gr.Column(scale=1, elem_classes="output-section"):
gr.Markdown("### ๐ Extracted Text", elem_classes="section-title")
text_output = gr.Textbox(
label="",
lines=6,
show_label=False,
placeholder="The extracted text will appear here...",
interactive=False
)
gr.Markdown("### ๐ Generated Audio", elem_classes="section-title")
audio_output = gr.Audio(
label="",
type="filepath",
show_label=False
)
# Connection
generate_btn.click(
fn=image_to_voice,
inputs=[image_input, voice_dropdown],
outputs=[audio_output, text_output],
show_progress="full"
)
# ===== TAB 2: Mood Chart =====
with gr.TabItem("๐ Mood Chart"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ค Upload Your Image", elem_classes="section-title")
mood_image_input = gr.Image(
label="",
type="pil",
height=350,
show_label=False
)
mood_analyze_btn = gr.Button(
"๐ Analyze Mood",
variant="primary",
elem_classes="generate-btn",
size="lg"
)
with gr.Column(scale=1):
gr.Markdown("### ๐ Mood Analysis Results", elem_classes="section-title")
mood_output = gr.Textbox(
label="",
lines=10,
show_label=False,
placeholder="Mood analysis will appear here...",
interactive=False
)
mood_analyze_btn.click(
fn=analyze_mood_from_image,
inputs=[mood_image_input],
outputs=[mood_output],
show_progress="full"
)
# ===== TAB 3: Story Generation =====
with gr.TabItem("๐ AI Story Generator"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ค Upload Your Image", elem_classes="section-title")
story_image_input = gr.Image(
label="",
type="pil",
height=350,
show_label=False
)
gr.Markdown("### ๐ญ Story Theme", elem_classes="section-title")
story_theme_dropdown = gr.Dropdown(
choices=[
"Adventure",
"Fantasy",
"Mystery",
"Romance",
"Science Fiction",
"Comedy",
"Educational",
"Inspirational"
],
label="Select Story Theme",
value="Adventure",
info="Choose a theme for your story"
)
story_generate_btn = gr.Button(
"โ๏ธ Generate Story",
variant="primary",
elem_classes="generate-btn",
size="lg"
)
with gr.Column(scale=1):
gr.Markdown("### ๐ Generated Story", elem_classes="section-title")
story_output = gr.Textbox(
label="",
lines=12,
show_label=False,
placeholder="Your story will appear here...",
interactive=False
)
story_generate_btn.click(
fn=ai_story_generation,
inputs=[story_image_input, story_theme_dropdown],
outputs=[story_output],
show_progress="full"
)
# ===== TAB 3B: Hugging Face Picture to Story =====
with gr.TabItem("๐จ HuggingFace Picture to Story"):
gr.Markdown("""
### ๐ค Advanced AI Story Generation using Hugging Face
This feature uses the cutting-edge **Vision Transformer (ViT) + GPT-2** model from Hugging Face
to directly transform your picture into a creative narrative story.
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ค Upload Your Picture", elem_classes="section-title")
hf_story_image_input = gr.Image(
label="",
type="pil",
height=350,
show_label=False
)
hf_story_generate_btn = gr.Button(
"๐ Transform to Story",
variant="primary",
elem_classes="generate-btn",
size="lg"
)
with gr.Column(scale=1):
gr.Markdown("### ๐ AI-Generated Story", elem_classes="section-title")
hf_story_output = gr.Textbox(
label="",
lines=14,
show_label=False,
placeholder="Your AI story will appear here...",
interactive=False
)
hf_story_generate_btn.click(
fn=huggingface_picture_to_story,
inputs=[hf_story_image_input],
outputs=[hf_story_output],
show_progress="full"
)
# ===== TAB 4: Study Helper =====
with gr.TabItem("๐ AI Study Helper"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ค Upload Your Study Material", elem_classes="section-title")
study_image_input = gr.Image(
label="",
type="pil",
height=350,
show_label=False
)
gr.Markdown("### ๐ฏ Study Assistance Type", elem_classes="section-title")
study_type_dropdown = gr.Dropdown(
choices=[
"Summary",
"Quiz Questions",
"Learning Tips",
"Note-Taking"
],
label="Select Study Aid",
value="Summary",
info="Choose the type of study assistance you need"
)
study_generate_btn = gr.Button(
"๐ Generate Study Aid",
variant="primary",
elem_classes="generate-btn",
size="lg"
)
with gr.Column(scale=1):
gr.Markdown("### ๐ Study Insights", elem_classes="section-title")
study_output = gr.Textbox(
label="",
lines=12,
show_label=False,
placeholder="Study insights will appear here...",
interactive=False
)
study_generate_btn.click(
fn=ai_study_helper,
inputs=[study_image_input, study_type_dropdown],
outputs=[study_output],
show_progress="full"
)
# ===== TAB 5: Study Helper for Kids =====
with gr.TabItem("๐จ Study Helper for Kids"):
gr.Markdown("""
# ๐ **WELCOME TO AWESOME LEARNING LAND!** ๐
๐ **Learning is FUN and EXCITING!**
Upload your homework, and let our super cool AI help you learn in amazing ways!
Choose your favorite learning style and get ready to become a LEARNING SUPERSTAR! ๐
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ค Upload Your Homework", elem_classes="section-title")
kids_study_image_input = gr.Image(
label="",
type="pil",
height=350,
show_label=False
)
gr.Markdown("### ๐ฎ Pick Your Learning Style", elem_classes="section-title")
kids_learning_style_dropdown = gr.Dropdown(
choices=[
"Fun Summary",
"Interactive Quiz",
"Memory Game",
"Learning Tips for Kids"
],
label="What sounds fun to you?",
value="Fun Summary",
info="Choose how you want to learn! ๐ฏ"
)
kids_study_generate_btn = gr.Button(
"๐ Start Learning Adventure!",
variant="primary",
elem_classes="generate-btn",
size="lg"
)
with gr.Column(scale=1):
gr.Markdown("### ๐ Your Learning Experience", elem_classes="section-title")
kids_study_output = gr.Textbox(
label="",
lines=14,
show_label=False,
placeholder="Your fun learning content will appear here! Get ready for an adventure! ๐",
interactive=False
)
kids_study_generate_btn.click(
fn=ai_study_helper_for_kids,
inputs=[kids_study_image_input, kids_learning_style_dropdown],
outputs=[kids_study_output],
show_progress="full"
)
gr.HTML("""
<div class="footer">
<p>Powered by <strong>Hugging Face Transformers</strong> & <strong>Supertonic TTS</strong> |
Built with โค๏ธ using Gradio</p>
</div>
""")
if __name__ == "__main__":
demo.launch()
|