jsakshi commited on
Commit
bfb4478
·
verified ·
1 Parent(s): 3898738

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -43
app.py CHANGED
@@ -586,70 +586,85 @@ demo.launch()'''
586
 
587
 
588
 
 
 
589
  import gradio as gr
590
  from transformers import pipeline
591
- import random
592
 
593
- # Load a lighter model (distilgpt2 is faster than TinyLlama)
594
  generator = pipeline("text-generation", model="distilgpt2", max_length=50, truncation=True)
595
 
596
  # Initialize story state
597
  story_history = []
598
 
599
- def generate_story_segment(prompt, user_choice=None):
600
- """Generate a short story segment and three specific options in one go."""
601
- if user_choice:
602
- prompt = f"{prompt} {user_choice}"
603
-
604
- # Single prompt for both story and choices
605
- combined_prompt = (
606
- f"Write a short paragraph (20-30 words) based on this: '{prompt}'. "
607
- "Then, list three short, specific options (1 sentence each) to expand the story logically."
608
  )
609
- output = generator(combined_prompt, max_length=100, num_return_sequences=1, do_sample=True, temperature=0.7)[0]["generated_text"]
610
- output = output.replace(combined_prompt, "").strip()
611
-
612
- # Split story and choices (assuming model outputs them sequentially)
613
- lines = output.split("\n")
614
- story_output = lines[0] if lines else prompt # Default to prompt if no story
615
- choices = lines[1:4] if len(lines) > 1 else []
616
-
617
- # Ensure the prompt is reflected
618
  prompt_words = set(prompt.lower().split())
619
  if not any(word in story_output.lower() for word in prompt_words):
620
  story_output = f"{prompt}. {story_output}"
621
-
622
- # Refine choices
623
- cleaned_choices = []
624
- for choice in choices:
625
- if len(choice) > 0 and len(choice.split()) > 3: # Ensure it’s a sentence
626
- cleaned_choices.append(choice[:50] + "..." if len(choice) > 50 else choice)
627
 
628
- # Fallback options if not enough choices
629
- while len(cleaned_choices) < 3:
630
- cleaned_choices.append(random.choice([
631
- f"{prompt.split()[0]} meets someone new.",
632
- f"{prompt.split()[0]} discovers a hidden secret.",
633
- f"{prompt.split()[0]} decides to leave home."
634
- ]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
 
636
- return story_output, cleaned_choices[:3]
637
 
638
  def start_story(initial_prompt):
639
  """Start the story with the user's initial prompt."""
640
  global story_history
641
  story_history = [initial_prompt]
642
- segment, choices = generate_story_segment(initial_prompt)
643
  story_history.append(segment)
644
- return "\n".join(story_history), choices[0], choices[1], choices[2]
 
645
 
646
  def continue_story(choice):
647
  """Continue the story based on the user's choice."""
648
  global story_history
649
- segment, choices = generate_story_segment(story_history[-1], choice)
650
  story_history.append(f"You chose: {choice}")
651
- story_history.append(segment)
652
- return "\n".join(story_history), choices[0], choices[1], choices[2]
 
 
 
 
 
 
 
 
 
653
 
654
  def reset_story():
655
  """Reset the story to start fresh."""
@@ -658,12 +673,12 @@ def reset_story():
658
  return "Story reset. Enter a new prompt to begin!", "", "", ""
659
 
660
  # Gradio interface
661
- with gr.Blocks(title="Story Builder") as demo:
662
- gr.Markdown("# Story Builder")
663
- gr.Markdown("Start with any prompt, and build your story step by step!")
664
 
665
  with gr.Row():
666
- prompt_input = gr.Textbox(label="Enter your story prompt (e.g., 'There is a boy named Sam')", placeholder="Type here...")
667
  start_button = gr.Button("Start Story")
668
 
669
  story_output = gr.Textbox(label="Your Story", lines=10, interactive=False)
 
586
 
587
 
588
 
589
+
590
+
591
  import gradio as gr
592
  from transformers import pipeline
 
593
 
594
+ # Load a lightweight model (distilgpt2) for initial story generation
595
  generator = pipeline("text-generation", model="distilgpt2", max_length=50, truncation=True)
596
 
597
  # Initialize story state
598
  story_history = []
599
 
600
+ def generate_initial_story(prompt):
601
+ """Generate a coherent initial story paragraph from the prompt."""
602
+ story_prompt = (
603
+ f"Write a short paragraph (30-40 words) introducing a story based on: '{prompt}'. "
604
+ "Keep it simple, coherent, and descriptive."
 
 
 
 
605
  )
606
+ story_output = generator(story_prompt, max_length=50, num_return_sequences=1, do_sample=True, temperature=0.7)[0]["generated_text"]
607
+ story_output = story_output.replace(story_prompt, "").strip()
608
+
609
+ # Ensure prompt relevance
 
 
 
 
 
610
  prompt_words = set(prompt.lower().split())
611
  if not any(word in story_output.lower() for word in prompt_words):
612
  story_output = f"{prompt}. {story_output}"
 
 
 
 
 
 
613
 
614
+ return story_output
615
+
616
+ def generate_options(story):
617
+ """Generate three specific, relevant options based on the story."""
618
+ # Extract key elements from the story for relevance
619
+ story_lower = story.lower()
620
+ character = story.split()[0] # Assume first word is the character (e.g., "Priya")
621
+
622
+ # Define option templates based on common story beats
623
+ if "town" in story_lower or "village" in story_lower:
624
+ options = [
625
+ f"{character} moves to a big city for a new job opportunity.",
626
+ f"{character} meets someone special who changes her life.",
627
+ f"{character} discovers a family secret that shocks her."
628
+ ]
629
+ elif "city" in story_lower:
630
+ options = [
631
+ f"{character} lands a dream job that tests her skills.",
632
+ f"{character} encounters a mysterious stranger in the crowd.",
633
+ f"{character} finds an old letter in her apartment."
634
+ ]
635
+ else:
636
+ options = [
637
+ f"{character} embarks on an unexpected adventure.",
638
+ f"{character} meets a friend who shares a bold idea.",
639
+ f"{character} uncovers a hidden truth about her past."
640
+ ]
641
 
642
+ return options
643
 
644
  def start_story(initial_prompt):
645
  """Start the story with the user's initial prompt."""
646
  global story_history
647
  story_history = [initial_prompt]
648
+ segment = generate_initial_story(initial_prompt)
649
  story_history.append(segment)
650
+ options = generate_options(segment)
651
+ return f"{segment}\n\n🔹 What happens next? Choose an option:\n1️⃣ {options[0]}\n2️⃣ {options[1]}\n3️⃣ {options[2]}", options[0], options[1], options[2]
652
 
653
  def continue_story(choice):
654
  """Continue the story based on the user's choice."""
655
  global story_history
 
656
  story_history.append(f"You chose: {choice}")
657
+ # Generate a new segment based on the choice
658
+ story_prompt = (
659
+ f"Continue this story: '{story_history[-1]} {choice}'. "
660
+ "Write a short paragraph (30-40 words) that builds on it logically."
661
+ )
662
+ story_output = generator(story_prompt, max_length=50, num_return_sequences=1, do_sample=True, temperature=0.7)[0]["generated_text"]
663
+ story_output = story_output.replace(story_prompt, "").strip()
664
+
665
+ story_history.append(story_output)
666
+ options = generate_options(story_output)
667
+ return f"{'\\n'.join(story_history)}\n\n🔹 What happens next? Choose an option:\n1️⃣ {options[0]}\n2️⃣ {options[1]}\n3️⃣ {options[2]}", options[0], options[1], options[2]
668
 
669
  def reset_story():
670
  """Reset the story to start fresh."""
 
673
  return "Story reset. Enter a new prompt to begin!", "", "", ""
674
 
675
  # Gradio interface
676
+ with gr.Blocks(title="Story Adventure") as demo:
677
+ gr.Markdown("# Story Adventure")
678
+ gr.Markdown("Begin your tale and shape it with your choices!")
679
 
680
  with gr.Row():
681
+ prompt_input = gr.Textbox(label="Enter your story prompt (e.g., 'Priya lives in a small town')", placeholder="Type here...")
682
  start_button = gr.Button("Start Story")
683
 
684
  story_output = gr.Textbox(label="Your Story", lines=10, interactive=False)