Spaces:
Sleeping
Sleeping
Commit Β·
67dff27
1
Parent(s): 1283f75
story agent
Browse filesFiles changed (10)
- Tools/audio_agent.pyAdded+131
- Tools/build_world.pyAdded+91
- Tools/extract_facts.pyAdded+96
- Tools/extract_image.pyAdded+46
- Tools/generate_choices.pyAdded+80
- Tools/image_agent.pyAdded+86
- Tools/imagedecider.pyAdded+77
- Tools/story_generator.pyAdded+123
- Tools/validate_consistency.pyAdded+50
- app.pyAdded+333
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# voice_narration_tool.py#-------------libraries to install----------##pip install g2p-en, nltk, smolagentsimport torchimport soundfile as sfimport nltkfrom transformers import FastSpeech2ConformerTokenizer, FastSpeech2ConformerWithHifiGanfrom smolagents import toolimport osimport warningswarnings.filterwarnings("ignore")nltk.download('all')
# ββββββββββββββββββββββββββββββ# Global FastSpeech2 model for voice narrationVOICE_MODEL = "espnet/fastspeech2_conformer_with_hifigan"_tokenizer_voice = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")_model_voice = FastSpeech2ConformerWithHifiGan.from_pretrained(VOICE_MODEL)_model_voice.eval()# ββββββββββββββββββββββββββββββ
@tooldef generate_voice_narration(text: str, output_filename: str = "narration.wav") -> str: """ Generate voice narration from text using FastSpeech2 TTS model. Args: text (str): The text to convert to speech output_filename (str): Output audio filename (default: "narration.wav") Returns: str: Path to the generated audio file """ try: # Clean and prepare text clean_text = text.strip() if not clean_text: return "Error: Empty text provided" # Tokenize the input text inputs = _tokenizer_voice(clean_text, return_tensors="pt") # Generate audio with torch.no_grad(): # Move inputs to same device as model if needed if torch.cuda.is_available() and next(_model_voice.parameters()).is_cuda: inputs = {k: v.cuda() if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} # Generate speech output = _model_voice(**inputs) audio = output.waveform.squeeze().cpu().numpy() # Ensure output directory exists os.makedirs(os.path.dirname(output_filename) if os.path.dirname(output_filename) else ".", exist_ok=True) # Save audio file sample_rate = 22050 # FastSpeech2 default sample rate sf.write(output_filename, audio, samplerate=sample_rate) return f"Voice narration saved to: {output_filename}" except Exception as e: return f"Error generating voice narration: {str(e)}"
@tooldef generate_story_narration(story_text: str, chapter_name: str = "chapter") -> str: """ Generate voice narration for story text, handling longer texts by splitting into sentences. Args: story_text (str): The story text to narrate chapter_name (str): Name prefix for the output file Returns: str: Status message with output file path """ try: # Clean text clean_text = story_text.strip() if not clean_text: return "Error: Empty story text provided" # For longer texts, we might want to split into sentences and combine # or just process the whole text at once (FastSpeech2 can handle reasonably long texts) output_filename = f"{chapter_name}_narration.wav" # Tokenize and generate inputs = _tokenizer_voice(clean_text, return_tensors="pt") with torch.no_grad(): # Move to appropriate device if torch.cuda.is_available() and next(_model_voice.parameters()).is_cuda: inputs = {k: v.cuda() if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} # Generate speech output = _model_voice(**inputs) audio = output.waveform.squeeze().cpu().numpy() # Save the narration sample_rate = 22050 sf.write(output_filename, audio, samplerate=sample_rate) # Calculate duration for user feedback duration = len(audio) / sample_rate return f"Story narration completed! Saved to: {output_filename} (Duration: {duration:.2f} seconds)" except Exception as e: return f"Error generating story narration: {str(e)}"
if __name__ == "__main__": # --- Test Cases --- test_texts = [ "The warrior stepped into the shadowy forest, his sword gleaming under the moonlight.....there appeared a monster and he said WHAT ARE YOU DOING I WILL KILL YOU ", "Captain Sarah Martinez floated weightlessly in the observation deck of the starship Enterprise.", "The old lighthouse keeper climbed the spiral stairs one last time, as the storm raged outside." ] print("Testing voice narration tool...") for i, text in enumerate(test_texts, 1): print(f"\nTest {i}: Generating narration for: '{text[:50]}...'") result = generate_voice_narration(text=text, output_filename=f"test_narration_{i}.wav") print(f"Result: {result}") # Test story narration story = " ".join(test_texts) print(f"\nTesting story narration with combined text...") story_result = generate_story_narration(story_text=story, chapter_name="test_story") print(f"Story Result: {story_result}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Tools/build_world.py
from typing import Dict, Anyfrom smolagents import toolimport jsonimport torch# from llm_utils import tokenizer, model, generate_completion # These are loaded globally elsewhere
@tooldef build_world(facts: Dict[str, Any]) -> Dict[str, Any]: """ Given a structured `facts` dictionary, returns a world-building dictionary with keys: - setting_description: a vivid 2β3 sentence paragraph describing the environment. - flora: a list of 3β5 plant species commonly found here. - fauna: a list of 3β5 animals or creatures one might encounter. - ambiance: a list of 3β5 sensory details (sounds, smells, tactile sensations).
Args: facts (Dict[str, Any]): The structured facts extracted from the scene.
Returns: Dict[str, Any]: A dictionary with exactly the four keys: 'setting_description', 'flora', 'fauna', and 'ambiance'. """ # 1) Prepare the JSON-extraction prompt facts_json = json.dumps(facts, indent=2) prompt = f"""You are a world-building assistant. Given these structured facts:
{facts_json}
Generate a JSON object with exactly these fields: 1) setting_description: a 2β3 sentence vivid paragraph describing the environment. 2) flora: a list of 3β5 plant species commonly found here. 3) fauna: a list of 3β5 animals or creatures one might encounter. 4) ambiance: a list of 3β5 sensory details (sounds, smells, tactile feelings).
Return ONLY valid JSON with those four keys."""
# 2) Tokenize & move to device inputs = tokenizer.apply_chat_template( [ {"role": "system", "content": "You convert structured facts into world-building JSON."}, {"role": "user", "content": prompt} ], tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True # Keep return_dict=True to get attention_mask ) # Move each tensor to the model device for k,v in inputs.items(): inputs[k] = v.to(model.device)
# 3) Generate up to 256 new tokens via shared generate_completion with torch.no_grad(): # Pass the input_ids tensor directly and the attention_mask outputs = model.generate( inputs["input_ids"], # Pass the tensor directly max_new_tokens=256, attention_mask=inputs.get("attention_mask") # Pass attention_mask if present )
# 4) Slice off the prompt tokens prompt_len = inputs["input_ids"].shape[-1] gen_ids = outputs[0][prompt_len:]
# 5) Decode the JSON string raw = tokenizer.decode(gen_ids, skip_special_tokens=True) start = raw.find("{") candidate = raw[start:] if start >= 0 else raw
# 6) Parse, with a defaults fallback defaults = { "setting_description": "", "flora": [], "fauna": [], "ambiance": [] } try: world_dict = json.loads(candidate) except Exception: world_dict = defaults.copy()
# 7) Ensure all keys are present for key, val in defaults.items(): world_dict.setdefault(key, val)
return world_dict123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# tools.py
from typing import Dict, Anyfrom smolagents import Toolfrom transformers import AutoTokenizer, AutoModelForCausalLMfrom llm_utils import tokenizer, model, generate_completionimport torchimport osimport json
class ExtractFactsTool(Tool): """ Extracts structured facts from a scene using a local Transformers LLM. """
name = "extract_facts" description = ( "Given a narrative paragraph, extracts and returns JSON with keys: " "location, weather, time_of_day, main_character, npc_states, " "inventory_items, events." )
inputs = { "scene_text": { "type": "string", "description": "The narrative paragraph from which to extract facts.", "required": True } } # Change output_type from "json" or "dict" to "object" output_type = "object"
def forward(self, scene_text: str) -> Dict[str, Any]: # 1) Build the instruction + content prompt prompt = f""" You are a fact-extraction assistant. Extract exactly the following keys and output valid JSON: 1) location: e.g. "rainy_forest" or null 2) weather: e.g. "rainy" or null 3) time_of_day: e.g. "evening" or null 4) main_character: protagonist name or null 5) npc_states: dict of other characters β {{status, location}}, or {{}} 6) inventory_items: list of item names, or [] 7) events: 1β2 sentence summary of what happened
Scene: \"\"\" {scene_text} \"\"\" """
# 2) Tokenize using the chat template # The output of apply_chat_template with return_tensors="pt" is a single tensor. # It does not need to be converted to a dictionary for model.generate. inputs_tensor = tokenizer.apply_chat_template( [{"role":"system","content":"You extract JSON facts."}, {"role":"user","content":prompt}], tokenize=True, add_generation_prompt=True, return_tensors="pt" ).to(model.device)
# 3) Generate up to 256 new tokens with torch.no_grad(): # Pass the tensor directly to generate outputs = model.generate(inputs_tensor, max_new_tokens=256)
# 4) Slice off the prompt tokens input_len = inputs_tensor.size(-1) # Use inputs_tensor to get the original input length gen_ids = outputs[0][input_len:]
# 5) Decode and strip out anything before the first '{' raw = tokenizer.decode(gen_ids, skip_special_tokens=True) json_start = raw.find("{") candidate = raw[json_start:] if json_start >= 0 else raw
# 6) Parse JSON (fallback to defaults on error) defaults = { "location": None, "weather": None, "time_of_day": None, "main_character": None, "npc_states": {}, "inventory_items": [], "events": "" } try: fact_dict = json.loads(candidate) except Exception: fact_dict = defaults.copy()
# 7) Ensure all required keys exist for k, v in defaults.items(): fact_dict.setdefault(k, v)
return fact_dict12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Tools/scene_extractor_tool.py
from typing import Dictfrom smolagents import toolfrom llm_utils import tokenizer, generate_completionimport torch
@tooldef extract_scene(context: str) -> str: """ Identify the key visual scene in one vivid paragraph (β€77 tokens). """ prompt = f"""You are a visual scene extractor. Given the text below,produce one vivid paragraph (max 77 tokens) describing the key visual moment. Return only that paragraph.
Text:\"\"\"{context}\"\"\"
Visual description:"""
inputs = tokenizer.apply_chat_template( [{"role":"system","content":"Extract a single visual scene."}, {"role":"user","content":prompt}], tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True ).to(tokenizer.device)
with torch.no_grad(): outputs = generate_completion(inputs, max_new_tokens=100, temperature=0.0, do_sample=False)
plen = inputs["input_ids"].shape[-1] gen_ids = outputs[0][plen:] raw = tokenizer.decode(gen_ids, skip_special_tokens=True).strip() # enforce token limit words = raw.split() if len(words) > 77: raw = " ".join(words[:77]) return raw1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Tools/generate_choices.py
from typing import Dict, Any, Listfrom smolagents import toolfrom llm_utils import tokenizer, model, generate_completionimport torchimport json
@tooldef generate_choices(scene_text: str, facts: Dict[str, Any]) -> List[str]: """ Generate 2β4 next-step choices for the reader based on the scene and facts.
Args: scene_text (str): The latest narrative paragraph. facts (Dict[str,Any]): Structured facts (location, weather, npc_states, etc.)
Returns: List[str]: A list of between 2 and 4 short choice strings. """ facts_json = json.dumps(facts, indent=2) prompt = f"""You are an interactive-story choice generator. Given the scene and known facts below,propose between 2 and 4 plausible next-step choices. Return *only* a JSON array of strings.
Scene:\"\"\"{scene_text}\"\"\"
Facts:{facts_json}
Requirements:- 2 to 4 concise, actionable choices (max one sentence each).- No extra commentaryβjust the JSON list."""
# wrap in a chat template messages = [ {"role": "system", "content": "You produce JSON arrays of story choices."}, {"role": "user", "content": prompt} ]
# tokenize & move to device inputs = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True ).to(model.device)
# generate with torch.no_grad(): outputs = model.generate(inputs, max_new_tokens=128)
# slice off prompt prompt_len = inputs["input_ids"].shape[-1] gen_ids = outputs[0][prompt_len:]
# decode, find JSON raw = tokenizer.decode(gen_ids, skip_special_tokens=True) start = raw.find("[") candidate = raw[start:] if start >= 0 else raw
# parse JSON, fallback try: choices = json.loads(candidate) if ( isinstance(choices, list) and 2 <= len(choices) <= 4 and all(isinstance(c, str) for c in choices) ): return choices except: pass
# fallback return ["Continue forward", "Turn back"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import osimport torchfrom PIL import Imagefrom diffusers import StableDiffusionPipeline, EulerDiscreteSchedulerimport warningsfrom smolagents import tool
warnings.filterwarnings("ignore")
# Global pipeline variable for reuse_pipeline = None
def get_pipeline(): """Initialize and return the Stable Diffusion pipeline.""" global _pipeline if _pipeline is None: try: device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.float16 if torch.cuda.is_available() else torch.float32 _pipeline = StableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5", torch_dtype=dtype, safety_checker=None, requires_safety_checker=False ).to(device) if hasattr(_pipeline, 'enable_attention_slicing'): _pipeline.enable_attention_slicing() except Exception as e: print(f"Failed to load pipeline: {e}") _pipeline = "mock" return _pipeline
@tooldef generate_image(scene_prompt: str) -> Image.Image: """ Generates a cartoon-style image from a scene prompt using Stable Diffusion v1.5. Falls back to a placeholder if loading fails. Args: scene_prompt (str): Description of the scene to generate Returns: PIL.Image.Image: Generated cartoon-style image """ pipe = get_pipeline() # Fallback to placeholder if pipeline loading failed if pipe == "mock": return Image.new('RGB', (512, 512), color='lightblue') # Enhance prompt for cartoon style prompt = f"cartoon style, {scene_prompt}, colorful, animated" # Generate image with fixed seed for reproducibility gen = torch.Generator(device=pipe.device).manual_seed(42) result = pipe( prompt, guidance_scale=7.5, num_inference_steps=20, height=512, width=512, generator=gen ) return result.images[0]
if __name__ == "__main__": # Test the function test_prompts = [ "Cartoon cat wearing a wizard hat in a magical forest", "Cartoon robot dancing in a disco with neon lights", "Cartoon dragon flying over a rainbow castle" ] for i, prompt in enumerate(test_prompts, 1): print(f"Generating image {i}: '{prompt}'") img = generate_image(prompt) print(f"Result: Image size={img.size}, mode={img.mode}") # Optionally save the image # img.save(f"test_image_{i}.png")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import torch# from transformers import AutoTokenizer, AutoModelForCausalLMfrom llm_utils import tokenizer, model, generate_completionfrom smolagents import toolimport warningswarnings.filterwarnings("ignore")
@tooldef check_significant_change(previous_context: str, current_context: str) -> int: """ Compare previous and current context; return 1 if major change (new scene/env), else 0. Args: previous_context (str): The previous context text current_context (str): The current context text Returns: int: 1 if major significant change detected, 0 otherwise """ prompt = f"""Compare these two contexts and determine if there is a major significant change (like a new scene, environment, or dramatic shift in situation). Reply with only "change" for a major significant change, or "unchange" if the contexts are similar or show minor differences.
Previous: {previous_context}Current: {current_context}
Answer (change or unchange):"""
# wrap in a chat template messages = [ {"role": "system", "content": "You detect significant changes between contexts. Reply only with 'change' or 'unchange'."}, {"role": "user", "content": prompt} ]
# tokenize & move to device inputs = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True ).to(model.device)
# generate with torch.no_grad(): outputs = generate_completion( **inputs, max_new_tokens=10, temperature=0.0, do_sample=False, pad_token_id=tokenizer.eos_token_id )
# slice off prompt prompt_len = inputs["input_ids"].shape[-1] gen_ids = outputs[0][prompt_len:]
# decode response raw = tokenizer.decode(gen_ids, skip_special_tokens=True) response = raw.strip().lower()
# check for change indicators if "change" in response and "unchange" not in response: return 1 else: return 0
if __name__ == "__main__": # --- Test Cases --- tests = [ ("John types at his desk in the morning light.", "John now types with a cup of coffee beside him."), ("Sarah walks through the quiet library browsing books.", "She stands on a cliff overlooking crashing waves."), ("Morning vendors set up at the market.", "The empty market is silent under the moonlight.") ] for i, (prev, curr) in enumerate(tests, 1): result = check_significant_change(previous_context=prev, current_context=curr) print(f"Test {i}: Prev='{prev}' | Curr='{curr}' -> Change Detected: {result}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# story_generator.py
from typing import Optionalimport os
from smolagents import Toolfrom huggingface_hub import InferenceClient
from transformers import AutoTokenizer, AutoModelForCausalLM, pipelineimport torchtorch.manual_seed(30)
HF_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN", "")MODEL_NAME = "deepseek-ai/DeepSeek-V3-0324"
if not HF_TOKEN: raise RuntimeError("Please set HUGGINGFACE_API_TOKEN in your environment.")
class StoryGeneratorTool(Tool): name = "story_generator" description = "Generates the next scene of an interactive story."
inputs = { "context": { "type": "string", "description": "Concatenated last N scenes + facts.", "required": True }, "initial_prompt": { "type": "string", "description": "The very first user prompt to start the story.", "required": False, "nullable": True }, "last_choice": { "type": "string", "description": "The userβs choice from the previous step.", "required": False, "nullable": True }, }
output_type = "string" _client: Optional[InferenceClient] = None
def _get_client(self) -> InferenceClient: if self._client is None: self._client = InferenceClient(token=HF_TOKEN) return self._client
def forward( self, context: str, initial_prompt: Optional[str] = None, last_choice: Optional[str] = None, ) -> str: if initial_prompt and last_choice: raise ValueError("Provide exactly one of `initial_prompt` or `last_choice`.")
# Build prompt if initial_prompt: system_content = ( "You are a children's-book style storyteller. Generate a vivid opening scene." ) user_content = f"User seed prompt:\n\"{initial_prompt}\"\n\nGenerate the opening scene."
elif last_choice: system_content = ( "You are a children's-book style storyteller. Continue from the last choice." ) user_content = ( f"Context:\n{context}\n\n" f"Last choice: \"{last_choice}\"\n\nGenerate the next scene." )
else: system_content = ( "You are a children's-book style storyteller. Continue based on context alone." ) user_content = f"Context:\n{context}\n\nGenerate the next scene."
messages = [ {"role": "system", "content": system_content}, {"role": "user", "content": user_content}, ]
# 1) Tokenize/conform the messages tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V3-0324") model = AutoModelForCausalLM.from_pretrained( "deepseek-ai/DeepSeek-V3-0324", device_map="auto", torch_dtype=torch.bfloat16 )
inputs = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_tensors="pt" ).to(model.device)
# 2) Generate outputs = model.generate(**inputs, max_new_tokens=400)
# 3) Extract only the generated portion (not the prompt) input_length = inputs["input_ids"].shape[-1] generated_ids = outputs[0][input_length:]
# 4) Decode and return scene_text = tokenizer.decode(generated_ids, skip_special_tokens=True) return scene_text
# client = self._get_client() # # Nonβstreaming chat call # resp = client.chat_completion( # model=MODEL_NAME, # messages=messages, # temperature=0.7, # max_tokens=400, # stream=False # )
# return 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# tools.py
from typing import Dict, Any, Listfrom smolagents import tool, Tool, InferenceClientModelfrom typing import Optionalimport jsonimport os
# Make sure your HF token is set in the environment already:# export HUGGINGFACE_API_TOKEN="Enter your hf token"HF_TOKEN = os.getenv("Enter your hf token", "")if not HF_TOKEN: raise RuntimeError("Please set HUGGINGFACE_API_TOKEN in your environment.")
# === Choose your HF model name here ===# For instance, "gpt2βhfβchat", or any chatβcapable endpoint. # If you are using a locallyβdeployed endpoint, point to its URL:# model_name = "https://api-inference.huggingface.co/models/your-username/your-chat-model"# If you want to use an HFβhosted chat LLM (e.g. a fineβtuned Llama 2), use:# model_name = "meta-llama/Llama-2-7b-chat-hf"model_name = "meta-llama/Llama-2-7b-chat-hf"
def _get_hf_client() -> InferenceClientModel: global _hf_client if _hf_client is None: _hf_client = InferenceClientModel( model_name=model_name, api_token=HF_TOKEN ) return _hf_client
@tooldef validate_consistency(old_facts: Dict[str, Any], new_facts: Dict[str, Any]) -> bool: """ Validate that the new_facts do not contradict the old_facts. For each core key ("location", "weather", "time_of_day"): - If old_facts[key] is not None and new_facts[key] is not None and they differ, return False (inconsistent). Otherwise, return True. """ core_keys = ["location", "weather", "time_of_day"]
for key in core_keys: old_val = old_facts.get(key) new_val = new_facts.get(key) if old_val is not None and new_val is not None and old_val != new_val: return True
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333import gradio as grimport osimport warningsfrom typing import Optional, Dict, Any
warnings.filterwarnings("ignore")
# Output directoriesAUDIO_DIR = "outputs/audio"os.makedirs(AUDIO_DIR, exist_ok=True)
# Mock implementations for story generation componentsclass StoryState: def __init__(self): self.scene_history = [] self.facts = [] self.world_meta = {} def get_context_window(self, n=3): return self.scene_history[-n:] if len(self.scene_history) > n else self.scene_history def update_facts(self, new_facts): self.facts.extend(new_facts) def append_scene(self, scene): self.scene_history.append(scene) def update_world_meta(self, meta): self.world_meta.update(meta) def to_dict(self): return { "scenes": len(self.scene_history), "facts": len(self.facts) }
class StoryGeneratorTool: def forward(self, context, initial_prompt=None, last_choice=None): if initial_prompt: return f"Story begins: {initial_prompt}\n\nThe adventure unfolds as mysterious events shape your path. You find yourself in an unfamiliar place, with shadows dancing around you and the sound of distant whispers filling the air. The path ahead splits into multiple directions, each promising different adventures and challenges." elif last_choice: return f"Following your choice to '{last_choice}', the story continues...\n\nYour decision leads you deeper into the mystery. New challenges emerge as the plot thickens. The environment around you shifts and changes, revealing hidden secrets and unexpected allies. What seemed like a simple choice now opens up entirely new possibilities for your adventure." else: return "The story continues with unexpected twists and turns. Ancient mysteries begin to unravel as you delve deeper into this strange world. Each step forward reveals new questions that demand answers, and you realize that your journey is far from over."
class ExtractFactsTool: def forward(self, scene_text): # Extract meaningful facts from scene text facts = [] if "mysterious" in scene_text.lower(): facts.append("There are mysterious elements in this world") if "path" in scene_text.lower(): facts.append("Multiple paths and choices are available") if "adventure" in scene_text.lower(): facts.append("This is an adventure-type story") if "challenge" in scene_text.lower(): facts.append("Challenges and obstacles exist") return facts if facts else [f"Story element: {scene_text[:30]}..."]
def build_world(facts): return { "world_complexity": len(facts), "narrative_depth": "high" if len(facts) > 5 else "medium", "story_themes": ["mystery", "adventure", "choice-driven"] }
def generate_choices(scene_text, facts): base_choices = [ "Investigate the mysterious occurrence further", "Seek help from potential allies nearby", "Explore the unknown path cautiously", "Take a bold and direct approach" ] # Customize choices based on scene content if "mystery" in scene_text.lower(): base_choices[0] = "Solve the mystery using your wits" if "danger" in scene_text.lower(): base_choices[3] = "Face the danger head-on" if "friend" in scene_text.lower() or "ally" in scene_text.lower(): base_choices[1] = "Rally your allies for support" return base_choices
def advance_story( state: StoryState, initial_prompt: Optional[str] = None, last_choice: Optional[str] = None) -> Dict[str, Any]: """ Runs one step of the story pipeline focusing on NLP """ # 1) Generate scene scene_tool = StoryGeneratorTool() scene_args = { "context": state.get_context_window(n=3), "initial_prompt": initial_prompt, "last_choice": last_choice, } scene_text = scene_tool.forward(**scene_args) # 2) Extract facts fact_tool = ExtractFactsTool() new_facts = fact_tool.forward(scene_text) # 3) Update state & build world metadata state.update_facts(new_facts) state.append_scene(scene_text) world_meta = build_world(state.facts) state.update_world_meta(world_meta) # 4) Generate next-step choices choices = generate_choices(scene_text, state.facts) # 5) Package and return return { "scene_text": scene_text, "choices": choices, "updated_state": state.to_dict(), }
# Global variables to store story statestory_state = StoryState()current_story = ""story_choices = []
def initialize_story(user_input): """Initialize the story with user input and generate first response""" global current_story, story_choices, story_state if not user_input.strip(): # Hide everything if empty return ( gr.update(visible=False, value=""), # chat_output gr.update(visible=False), # choice1 gr.update(visible=False), # choice2 gr.update(visible=False), # choice3 gr.update(visible=False), # choice4 gr.update(visible=False), # prev_btn gr.update(visible=False), # next_btn gr.update(visible=True, value=""), # keep user_input visible gr.update(visible=True), # keep submit_btn visible gr.update(visible=False) # choices_header ) # Reset story state story_state = StoryState() # Generate story using pipeline result = advance_story(story_state, initial_prompt=user_input) # Update global state current_story = result["scene_text"] story_choices = result["choices"] print(f"Generated story: {current_story}") print(f"Generated choices: {story_choices}") # Return updates return ( gr.update(visible=True, value=current_story), # chat_output gr.update(visible=True, value=story_choices[0]), # choice1 gr.update(visible=True, value=story_choices[1]), # choice2 gr.update(visible=True, value=story_choices[2]), # choice3 gr.update(visible=True, value=story_choices[3]), # choice4 gr.update(visible=True), # prev_btn gr.update(visible=True), # next_btn gr.update(visible=False), # hide user_input gr.update(visible=False), # hide submit_btn gr.update(visible=True) # show choices_header )
def make_choice(choice_num): """Handle story choice selection and generate next scene""" global current_story, story_choices, story_state if choice_num < len(story_choices): selected_choice = story_choices[choice_num] print(f"User selected choice {choice_num}: {selected_choice}") # Generate next story scene result = advance_story(story_state, last_choice=selected_choice) # Update global state current_story = result["scene_text"] story_choices = result["choices"] print(f"Generated new story: {current_story}") print(f"Generated new choices: {story_choices}") return ( gr.update(value=current_story), # chat_output gr.update(value=story_choices[0]), # choice1 gr.update(value=story_choices[1]), # choice2 gr.update(value=story_choices[2]), # choice3 gr.update(value=story_choices[3]) # choice4 ) return tuple([gr.update()]*5)
def go_previous(): """Navigate to previous story segment""" global story_state, current_story if len(story_state.scene_history) > 1: # Get previous scene prev_scene = story_state.scene_history[-2] return gr.update(value=f"π Previous Scene:\n\n{prev_scene}") return gr.update(value="π No previous story segment available")
def go_next(): """Navigate back to current story segment""" global current_story return gr.update(value=current_story)
def restart_story(): """Restart the story from beginning""" global story_state, current_story, story_choices story_state = StoryState() current_story = "" story_choices = [] return ( gr.update(visible=False, value=""), # chat_output gr.update(visible=False), # choice1 gr.update(visible=False), # choice2 gr.update(visible=False), # choice3 gr.update(visible=False), # choice4 gr.update(visible=False), # prev_btn gr.update(visible=False), # next_btn gr.update(visible=True, value=""), # show user_input gr.update(visible=True), # show submit_btn gr.update(visible=False) # hide choices_header )
# Create the Gradio interfacewith gr.Blocks(title="AI Story Generation Platform", theme=gr.themes.Soft(), css=""" .enter-button { margin-top: 20px !important; } .story-output { font-family: 'Georgia', serif !important; line-height: 1.6 !important; } .choice-button { margin: 5px !important; padding: 10px !important; } .nav-button { margin: 10px 5px !important; } .restart-button { margin-top: 20px !important; background: #ff6b6b !important; }""") as demo: gr.Markdown("# π AI Interactive Story Generation Platform") gr.Markdown("Enter your story idea to begin an interactive text-based adventure!") # Input section user_input = gr.Textbox( placeholder="Enter your story beginning (e.g., 'I wake up in a mysterious forest...')", label="Story Input", lines=3 ) submit_btn = gr.Button("π Start Adventure", variant="primary", elem_classes="enter-button")
# Story output chat_output = gr.Textbox( label="π Your Story", lines=8, interactive=False, visible=False, elem_classes="story-output" ) # Choices section choices_header = gr.Markdown("### π― Choose Your Next Action", visible=False) with gr.Row(): choice1_btn = gr.Button("Choice 1", visible=False, variant="secondary", elem_classes="choice-button") choice2_btn = gr.Button("Choice 2", visible=False, variant="secondary", elem_classes="choice-button") with gr.Row(): choice3_btn = gr.Button("Choice 3", visible=False, variant="secondary", elem_classes="choice-button") choice4_btn = gr.Button("Choice 4", visible=False, variant="secondary", elem_classes="choice-button") # Navigation section with gr.Row(): prev_btn = gr.Button("β¬
οΈ Previous Scene", visible=False, variant="outline", elem_classes="nav-button") next_btn = gr.Button("Current Scene β‘οΈ", visible=False, variant="outline", elem_classes="nav-button") restart_btn = gr.Button("π Restart Story", visible=False, variant="stop", elem_classes="restart-button") # Story statistics story_stats = gr.Markdown("", visible=False) # Event handlers submit_btn.click( fn=initialize_story, inputs=[user_input], outputs=[ chat_output, choice1_btn, choice2_btn, choice3_btn, choice4_btn, prev_btn, next_btn, user_input, submit_btn, choices_header ] ).then( fn=lambda: gr.update(visible=True), outputs=[restart_btn] ) # Choice event handlers choice1_btn.click( fn=lambda: make_choice(0), outputs=[chat_output, choice1_btn, choice2_btn, choice3_btn, choice4_btn] ) choice2_btn.click( fn=lambda: make_choice(1), outputs=[chat_output, choice1_btn, choice2_btn, choice3_btn, choice4_btn] ) choice3_btn.click( fn=lambda: make_choice(2), outputs=[chat_output, choice1_btn, choice2_btn, choice3_btn, choice4_btn] ) choice4_btn.click( fn=lambda: make_choice(3), outputs=[chat_output, choice1_btn, choice2_btn, choice3_btn, choice4_btn] ) # Navigation event handlers prev_btn.click(fn=go_previous, outputs=[chat_output]) next_btn.click(fn=go_next, outputs=[chat_output]) # Restart handler restart_btn.click( fn=restart_story, outputs=[ chat_output, choice1_btn, choice2_btn, choice3_btn, choice4_btn, prev_btn, next_btn, user_input, submit_btn, choices_header ] ).then( fn=lambda: gr.update(visible=False), outputs=[restart_btn] )
if __name__ == "__main__": demo.launch()Tools/audio_agent.pyAdded+131
Tools/build_world.pyAdded+91
Tools/extract_facts.pyAdded+96
Tools/extract_image.pyAdded+46
Tools/generate_choices.pyAdded+80
Tools/image_agent.pyAdded+86
Tools/imagedecider.pyAdded+77
Tools/story_generator.pyAdded+123
Tools/validate_consistency.pyAdded+50
app.pyAdded+333