Files
talemate/tests/test_dialogue_cleanup.py

476 lines
16 KiB
Python
Raw Permalink Normal View History

Prep 0.15.0 (#38) * send one request for assign all clients * tweak narrate-after-dialogue prompt * elevenlabs default to turbo model and make model id configurable * improve add client dialogue to be more robust * prompt for default character creation on character card loads * rename to model as to not conflict with pydantic * narrate after dialogue strip dialogue generation unless enabled via new option * starling and capybara-tess * narrate dialogue context increased * relabel tts agent to Voice, show agent label in status bar * dont expect LLM to handle * and " - most of them are not stable / consistent enough with it * starling template updated * if allow dialogue in narration is disabled just assume the entire string is a narration * reorganization the narrate after dialogue template * fix more issues with time passage calculations * move punkt download to agent init and silence * improved RAG during conversation if AI selected is enabled in conversation agent * prompt tweaks * deepseek, chromomaid-storytelling * relock * narrate-after-dialogue prompt tweaks * runpod status queries every 15 secs instead of 60 * default player character prompting when loading character card from talemate storage * better chunking during split tts generation * tweak narrate progress prompt * improvements to ensure_dialogue_format and tests * to pytest * prep 0.15.0 * update packages * dialogue cleanup fixes * fix openai default model name fix not being able to edit client due to name check * free form analyst was using wrong system prompt causing gpt-4 to actually generate json responses
2023-12-02 00:40:14 +02:00
import pytest
0.29.0 (#167) * set 0.29.0 * tweaks for dig layered history (wip) * move director agent to directory * relock * remove "none" from dig_layered_history response * determine character development * update character sheet from character development (wip) * org imports * alert outdated template overrides during startup * editor controls normalization of exposition * dialogue formatting refactor * fix narrator.clean_result forcing * regardless of editor fix exposition setting * move more of the dialogue cleanup logic into the editor fix exposition handlers * remove cruft * change ot normal selects and add some margin * move formatting option up * always strip partial sentences * separates exposition fixes from other dialogue cleanup operations, since we still want those * add novel formatting style * honor formatting config when no markers are supplied * fix issue where sometimes character message formatting would miss character name * director can now guide actors through scene analysis * style fixes * typo * select correct system message on direction type * prompt tweaks * disable by default * add support for dynamic instruction injection and include missing guide for internal note usage * change favicon and also indicate business through favicon * img * support xtc, dry and smoothing in text gen webui * prompt tweaks * support xtc, dry, smoothing in koboldcpp client * reorder * dry, xtc and smoothing factor exposed to tabby api client * urls to third party API documentation * remove bos token * add missing preset * focal * focal progress * focal progress and generated suggestions progress * fix issue with discard all suggestions * apply suggestions * move suggestion ux into the world state manager * support generation options for suggestion generation * unused import * refactor focal to json based approach * focal and character suggestion tweaks * rmeove cruft * remove cruft * relock * prompt tweaks * layout spacing updates * ux elements for removal of scenes from quick load menu * context investigation refactor WIP * context investigation refactor * context investigation refactor * context investigation refactor * cleanup * move scene analysis to summarizer agent * remove deprecated context investigation logic * context investigation refactor continued - split into separate file for easier maint * allow direct specification of response context length * context investigation and scene analyzation progress * change analysis length config to number * remove old dig-layered-history templates * summarizer - deep analysis is only available if there is layered history * move world_state agent to dedicated directory * remove unused imports * automatic character progression WIP * character suggestions progress * app busy flag based on agent business * indicate suggestions in world state overview * fix issue with user input cleanup * move conversation agent to a dedicated submodule * Response in action analyze_text_and_extract_context is too short #162 * move narrator agent to its own submodule * narrator improvements WIP * narration improvements WIP * fix issue with regen of character exit narration * narration improvements WIP * prompt tweaks * last_message_of_type can set max iterations * fix multiline parsing * prompt tweaks * director guide actors based of scene analysis * director guidance for actors * prompt tweaks * prompt tweaks * prompt tweaks * fix automatic character proposals not propagating to the ux * fix analysis length * support director guidance in legacy chat format * typo * prompt tweaks * prompt tweaks * error handling * length config * prompt tweaks * typo * remove cruft * prompt tweak * prompt tweak * time passage style changes * remove cruft * deep analysis context investigations honor call limit * refactor conversation agent long term memory to use new memory rag mixin - also streamline prompts * tweaks to RAG mixin agent config * fix narration highlighting * context investgiation fixes director narration guidance summarization tweaks * direactor guide narration progress context investigation fixes that would cause looping of investigations and failure to dig into the correct layers * prompt tweaks * summarization improvements * separate deep analysis chapter selection from analysis into its own prompt * character entry and exit * cache analysis per subtype and some narrator prompt tweaks * separate layered history logic into its own summarizer mixin and expose some additional options * scene can now set an overral writing style using writing style templates narrator option to enable writing style * narrate query writing style support * scene tools - narrator actions refactor to handler and own component * narrator query / look at narrations emitted as context investigation messages refactor context investigation messaage display scene message meta data object * include narrative direction * improve context investigation message prompt insert * reorg supported parameters * fix bug when no message history exists * WIP make regenerate work nicely with director guidance * WIP make regenerate work nicely with director guidance * regenerate conversation fixes * help text * ux tweaks * relock * turn off deep analysis and context investigations by default * long term memory options for director and summarizer * long term memory caching * fix summarization cache toggle not showing up in ux * ux tweaks * layered history summarization includes character information for mentioned characters * deepseek client added * Add fork button to narrator message * analyze and guidance support for time passage narration * cache based on message fingerprint instead of id * configurable system prompts WIP * configurable system prompts WIP * client overrides for system prompts wired to ux * system prompt overhaul * fix issue with unknown system prompt kind * add button to manually request dynamic choices from the director move the generate choices logic of the director agent to its own submodule * remove cruft * 30 may be too long and is causing the client to disappear temporarly * suppoert dynamic choice generate for non player characters * enable `actor` tab for player characters * creator agent now has access to rag tools improve acting instruction generation * client timeout fixes * fix issue where scene removal menu stayed open after remove * expose scene restore functionality to ux * create initial restore point * fix creator extra-context template * didn't mean to remove this * intro scene should be edited through world editor * fix alert * fix partial quotes regardless of editor setting director guidance for conversation reminds to put speech in quotes * fix @ instructions not being passed through to director guidance prompt * anthropic mode list updated * default off * cohere model list updated * reset actAs on next scene load * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * remove debug cruft * relock * docs on changing host / port * fix issue with narrator / director actiosn not available on fresh install * fix issue with long content classification determination result * take this reminder to put speech into quotes out for now, it seems to do more harm than good * fix some remaining issues with auto expositon fixes * prompt tweaks * prompt tweaks * fix issue during reload * expensive and warning ux passthrough for agent config * layered sumamry analysation defaults to on * what's new info block added * docs * what's new updated * remove old images * old img cleanup script * prompt tweaks * improve auto prompt template detection via huggingface * add gpt-4o-realtime-preview add gpt-4o-mini-realtime-preview * add o1 and o3-mini * fix o1 and o3 * fix o1 and o3 * more o1 / o3 fixes * o3 fixes
2025-02-01 17:44:06 +02:00
from talemate.util import ensure_dialog_format, clean_dialogue, remove_trailing_markers
Prep 0.15.0 (#38) * send one request for assign all clients * tweak narrate-after-dialogue prompt * elevenlabs default to turbo model and make model id configurable * improve add client dialogue to be more robust * prompt for default character creation on character card loads * rename to model as to not conflict with pydantic * narrate after dialogue strip dialogue generation unless enabled via new option * starling and capybara-tess * narrate dialogue context increased * relabel tts agent to Voice, show agent label in status bar * dont expect LLM to handle * and " - most of them are not stable / consistent enough with it * starling template updated * if allow dialogue in narration is disabled just assume the entire string is a narration * reorganization the narrate after dialogue template * fix more issues with time passage calculations * move punkt download to agent init and silence * improved RAG during conversation if AI selected is enabled in conversation agent * prompt tweaks * deepseek, chromomaid-storytelling * relock * narrate-after-dialogue prompt tweaks * runpod status queries every 15 secs instead of 60 * default player character prompting when loading character card from talemate storage * better chunking during split tts generation * tweak narrate progress prompt * improvements to ensure_dialogue_format and tests * to pytest * prep 0.15.0 * update packages * dialogue cleanup fixes * fix openai default model name fix not being able to edit client due to name check * free form analyst was using wrong system prompt causing gpt-4 to actually generate json responses
2023-12-02 00:40:14 +02:00
0.30.0 (#184) * pytorch update * github workflow for tests * tests set up config * tests download nltk punkt * punkt_tab * fix world state not updating on new initial scene load * fix new character creation from scene tools * py 312 py 313 support remove unreliant cuda detection and just lock poetry with cuda * fix tests * dont auto install cuda * remove unused StrEnum import * separate cuda install * fix auto progress OFF no longer working * fix debug logging options not sticking * disable revision during image prompt generation * prompt tweaks * prompt tweaks * fix some issues with directed character creation * tweak the continue generation button so its less prone to pop into a new line on itsown * fix context db filter field layout * handle error when trying to regnerate passthrough narrator message * prompt tweaks * increase auto direct evaluation length * fix node library on windows * auto direct eval tweaks * prompt tweaks * prompt tweaks * allow updationg of scene phase through director console * add generate action to director console phase intent text fields * prompt tweaks * track iteration count in scene loop always yield to user at initial start / load of a scene * fix issue with Split and Join nodes when passed \n as delimiter * sim suite only generate auto direct requirements if auto direct is enabled sim suite fix issues with title generation * autocomplete button disable until there is text to autcomplete * update installation docs * update scenario tools docs * docs * writing style phrase detection * typo * docs * fix issue where deleting an applied preset group would prevent selection of a different preset group in the affected client * fix @-Instruction is broken when using apostrophes * editor never attempt to fix exposition on user input if input starts with command characters @, ! or / * prompt tweaks * editor revision: automatic revision setting, prompt tweaks, docs * missing files * fix issue where narration responses starting with # would result in empty messages * prompt tweaks * fix issue with autocomplete not working at the beginning of a scene * fix issues where cached guidance would result in no guidance * editor revision analysis now has access to scene analysis and director guidance if it exists * fix issue where all nodes in the node editor would be locked on winsows OS * add `scene/SetIntroducation` node * fix issue where generating narration in a scene with zero characters would always come back blank * SceneIntroduction node state output fixed * node editor docs progress * fix issue with loading scene from file upload no longer working * better handling of what to do when there are no characters in a scene and no default character is defined * typo * silence trigger game loop debug message * docs * GenerateThematicList node * docs * docs * stubs * allow creation of module from existing nodes * move function into plugin * separate graph export functions into own .js file * group from selected nodes * remove debug output * tweak create module dialog * docs * docs * graph tests need to assume auto_progres True * add ModuleProperty node * fix some issues in the module creation modal when extending or copying a module * include module name in module deletion confirm dialog * fix node module copy not setting updated registry * module property name output * docs * docs * initializing a scene from a character card will no longer break the node editor * docs * when greeting text and intro do not match, do the greeting text first. * intro is set during card import, there is no need to ever emit character greetings in addition to the intro, its not really something that matches talemate's design philsophy at this point * docs * dynamic premise modules * tweaks * propagate module level property defaults to node * docs * fix issue where the default character would get added to scenes during load even though there already was a player character * prompt tweaks * tweaks to generate-premise module * docs * infinity quest dynamic story v2 * tweaks limits * fix line endings * prompt tweaks * fix some issues with node property editing * formatting * prompt tweaks * group and comment * add talemate tint node style fix gap in nodes when there are no sockets * node style fixes * docs * docs * icon for swtich nodes * conditional emit status node * don't reset dynamic premise * dynamic premise tweaks * dynamic premis status messages * fix issue with Input value error node * validate that topic is specified * fix issue where cancelling a generation triggered during scene loop init would cause the loop to reinitialize * docs * node error handling improvements * docs * better error handling in generate premise module * a connected socket should always override a property of the same value even if the socket connection is not resolved * dynamic premise expose intro length property * fix some issues with node module creation and add registry path validation * correctly title creative loop module so it can be copied * remove debug message * rename to dynamic storyline for clarity and so it doesn't collide with tutorial * import dynanimc storyline node * docs * gracefully handle a node missing during graph load * docs * make agent list a bit more compact * disable node property editing in inherited nodes * rename editor revision events so they are inline with the other agent events * support instruction injection for director.generate_choices action * normalize dynamic instructions * fix director guidance dynamic instructions * docs * generate choices event add choices property * prompt tweaks * add dynamic instruction node * prompt tweak * fix issue where some events could not be hooked into through event node modules * docs * clean response node * docs * docs * docs * module library tweaks * fix some issues with act-as selection * dont allow creation of new modules until scene has been saved at least once * public node modules dir * sim suite module styles * remove debug messages * fix default node titles * fix number input vlaidation in math nodes * context awareness in contextual generate now includes character info * fix dupe id warnings * alt drag to clone multiple nodes * alt drag to clone multiple nodes * docs * docs * fix issue where some scene modules could leak across scenes * dynamic instructions already included through extra context * prompt tweaks * update defaults * docs * make list init from json * socs * fix issue where not all field definitions would get sent * docs * fix issue causing deep analysis to loop * case insentive regex matching * prompt tweaks * fix node title * fix size issue in scene view when node editor was open on smaller resolutions * fix issue with autocomplete sometime loosing markup * add claude 4 * make director guidance and actor instructions available to autocomplete prompt * fix trim node handling of \n * extract node * extract node trim property * remover cruft * charactermessage node only set character if not already part of message prefix * editor revision unslop mode * fix search scenes showing node module files * prompt tweaks * unslop support unwanted phrase detection * define bad_prose * </FIX> seems to get ommitted a lot so lets handle it * cleanup * return on no issues * fix some issues with character creation * fix some character creation issues * prompt tweaks * contewxtual generate and autocomplete signals added * prefix revision_ * use uuidv4 which is already installed and doesnt come with compatibility issues * editor revision support for contextual generations normalize some event objects * add template picker to worldstate character creation interface * prompt tweaks * dont unslop scene intent or story intent generation * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * fix issue of conversation losing edits through signals * support revisions for world state entry generation * task_instructions * dont show rewrite specific options if unslop method is selected * docs * fix issue with setting locked save file when auto saving was turned on * don't trigger player_turn_start in creative mode * better check for when to fire player_turn_start and when not * node editor crash course fixes * docs * fix issue where sometimes wrong system prompt was selected * add world context to contextual generate node * fix node dragging issue when cloning multiple nodes * support editor revision for summarization generation * summarization support dynamic instructions * dedicated template for summary unslop * pass summarization_history to template vars * prompt tweaks * prompt tweaks * not sure how this got blanked * wording * wording * only display debug log if TALEMATE_DEBUG=1 * fix syntax * fix syntax * remove unused cruft * start-debug * log message cleanup * docs * tweak defaults * sim suite polish * remove unused images * add writing style instructions to revision prompts * missing endif tag * prompt tweaks * prompt tweaks * prompt tweaks * use app-busy * prompt tweaks * update readme and screenshots wording wording * add discord link
2025-06-03 12:26:12 +03:00
MULTILINE_TEST_A_INPUT = """
\"The first line.
The second line.
- list item
- list item
The third line.\"
"""
MULTILINE_TEST_A_EXPECTED = """
\"The first line.
The second line.
- list item
- list item
The third line.\"
"""
@pytest.mark.parametrize(
"input, expected",
[
("Hello how are you?", "Hello how are you?"),
('"Hello how are you?"', '"Hello how are you?"'),
(
'"Hello how are you?" he asks "I am fine"',
'"Hello how are you?" *he asks* "I am fine"',
),
(
"Hello how are you? *he asks* I am fine",
'"Hello how are you?" *he asks* "I am fine"',
),
(
'Hello how are you?" *he asks* I am fine',
'"Hello how are you?" *he asks* "I am fine"',
),
(
'Hello how are you?" *he asks I am fine',
'"Hello how are you?" *he asks I am fine*',
),
(
'Hello how are you?" *he asks* "I am fine" *',
'"Hello how are you?" *he asks* "I am fine"',
),
(
'"Hello how are you *he asks* I am fine"',
'"Hello how are you" *he asks* "I am fine"',
),
(
"This is a string without any markers",
"This is a string without any markers",
),
(
'This is a string with an ending quote"',
'"This is a string with an ending quote"',
),
(
"This is a string with an ending asterisk*",
"*This is a string with an ending asterisk*",
),
('"Mixed markers*', "*Mixed markers*"),
(
'*narrative.* dialogue" *more narrative.*',
'*narrative.* "dialogue" *more narrative.*',
),
(
'"*messed up dialogue formatting.*" *some narration.*',
'"messed up dialogue formatting." *some narration.*',
),
(
'*"messed up narration formatting."* "some dialogue."',
'"messed up narration formatting." "some dialogue."',
),
(
"Some dialogue and two line-breaks right after, followed by narration.\n\n*Narration*",
'"Some dialogue and two line-breaks right after, followed by narration."\n\n*Narration*',
),
(
'*Some narration with a "quoted" string in it.* Then some unquoted dialogue.\n\n*More narration.*',
'*Some narration with a* "quoted" *string in it.* "Then some unquoted dialogue."\n\n*More narration.*',
),
(
"*Some narration* Some dialogue but not in quotes. *",
'*Some narration* "Some dialogue but not in quotes."',
),
(
"*First line\nSecond line\nThird line*",
"*First line\nSecond line\nThird line*",
),
(MULTILINE_TEST_A_INPUT, MULTILINE_TEST_A_EXPECTED),
],
)
Prep 0.15.0 (#38) * send one request for assign all clients * tweak narrate-after-dialogue prompt * elevenlabs default to turbo model and make model id configurable * improve add client dialogue to be more robust * prompt for default character creation on character card loads * rename to model as to not conflict with pydantic * narrate after dialogue strip dialogue generation unless enabled via new option * starling and capybara-tess * narrate dialogue context increased * relabel tts agent to Voice, show agent label in status bar * dont expect LLM to handle * and " - most of them are not stable / consistent enough with it * starling template updated * if allow dialogue in narration is disabled just assume the entire string is a narration * reorganization the narrate after dialogue template * fix more issues with time passage calculations * move punkt download to agent init and silence * improved RAG during conversation if AI selected is enabled in conversation agent * prompt tweaks * deepseek, chromomaid-storytelling * relock * narrate-after-dialogue prompt tweaks * runpod status queries every 15 secs instead of 60 * default player character prompting when loading character card from talemate storage * better chunking during split tts generation * tweak narrate progress prompt * improvements to ensure_dialogue_format and tests * to pytest * prep 0.15.0 * update packages * dialogue cleanup fixes * fix openai default model name fix not being able to edit client due to name check * free form analyst was using wrong system prompt causing gpt-4 to actually generate json responses
2023-12-02 00:40:14 +02:00
def test_dialogue_cleanup(input, expected):
Prep 0.17.0 (#48) * improve windows install script to check for compatible python versions, also work with multi version python installs * bunch of llm prompt templates * first gamestate directing impl * lower similarity threshold when checking for repetition in llm responses * tweaks to narrate after dialog prompt tweaks to extract character sheet prompt * set_context cmd * Xwin MoE * thematic generator for randomized content stimuli * add a memory query to extract character sheet * direct-scene prompt tweaks * conversation prompt tweaks * inline character creation from gameplay instruction template expose thematic generator to prompt templates * Mixtral Synthia-MoE * display prompt and response side by side * improve ensure_dialogue_format * prompt tweaks * prevent double passive narration in one round improvements to persist character logic * SlimOrca OpenBuddy * prompt tweaks * runpod status check wrapped in asyncio * generate_json_list creator agent action * limit conversation retries to 2 fix issue where REPETITION signal trigger would get sent with the prompt * smaller agent tweaks * thematic generator personality list thematic generator generate from sets of lists * adjust tests * mistral prompt adjustment * director: update content context * prompt adjustments * nous-hermes-2-yi dolphin-2.2-yo dolphin-2.6-mixtral * status messages * determine character goals generate json lists * fix error when chromadb add was called before db was ready (wait until the db is fully initiazed) * only strip extra spaces off of prompt textgenwebui: half temperature on -yi- models * prompt tweaks * more thematic generators * direct scene without character should just run the scene instructions if they exist * as_question_answer for query_scene * context_history revamp * Aurora-Nights MixtgralOrochi dolphin-2.7-mixtral nous-hermas-2-solar * remove old context_history calls * mv world_state.py to subdir FlatDolphinMaid Goliath Norobara Nous-Capybara * world state manager first progress * context db manager * fix issue with some clients not remembering context length settings after talemate restart * Sensualize-Solar * improve RAG prompt * conversation agent use [ as a stopping string since the new reinforcement messages use that * new method for RAG during conversation * mixtral_11bx2_moe * option to reset context db from manager ui * fix context db cleanup if scene is closed without saving * didnt mean to commit that * hide internal meta tags * keep track of manual context entries in scene save file so it can be rebuilt. * auto save auto progress quick settings hotbar options * manual mode actor dialogue tools refactor toolbar * narrate directed progress reorganiza narration tools into one cmd module * 0.17.0 * Mixtral_34Bx2 Sensualize-Mixtral openchat * fix save-as action * fix issue where too little context was joined in via RAG * context pins implementation * show active pins in world state component * pin condition eval and world state agent action config * Open_Gpt4 * summarization prompt improvements system prompt for summarization * guidance prompt for time passage narration * fix rerun for generic / unhandled messages * prompt fixes * summarization methods * prompt adjustments * world tools to hot bar ux tweaks * bagel-dpo * context state reinforcements support different insertion methods now (sequential, all context or conversation specific context) * first progress on world state reinforcement templating * Kunoichi * tweaks to update reinforcements prompt * world state templates progress * world state templates integration into main ux * fix issue where openai client wouldn't accept context length override * dont reconfigure client if no arguments are provided * pin condition prompt fixes world state apply template comman label set * world information / lore entries and reinforcement * show world entry states reinforcers in ux * gitignore * dynamic scenario generation progress * dynamic scenario experiment * gitignore * need to emit world state even if we dont run it during scene init * summarize and pin action * poetry relock * template question / attribute cannot be empty * fix issue with summarize and pin not respecting selected line * keep reinforcement messages in history, but keep the same one from stacking up * narrate query prompt more natural sounding response * manage pins from world entry editor * pin_only tag * ts aware summarize and pin pin text rendered to context with time label context reuse session id (this fixes issue of editing context entry and not saving the scene causing removal of context entry next time scene is loaded) * UX to add character state from template within the worldstate manager UX * move divider * handle agent emit error fix issue with state reinforcer validation * layout fixes in world state character panel physical health template added to example config * fix pin_only undefined error in world entry editor * laser-dolphin Noromaid-v0.4-Mixtral-Instruct * show state templates for world and players in favorite list fix applying world state template * refresh world entry list on state creation * changing a state from non-sequential to sequential should queue it as due * quicksettings to bar * fix error during memory db delete * status messages during scene load * removing a sequential state reinforcement should remove the reinforcement messages * Nous-Hermes-2-Mixtral * fix sync issue when editing character details through contextdb * immutable save property * enable director * update example config * enable director when loading a scene file that has instructions * fix more openai client funkyness with context size and losing model * iq dyn scenario prompt fixes * delay client save so that dragging the ctx slider doesnt send off a million requests default openai ctx to 8k * input disabled while clients active * declare event * narrate query prompt tweaks * fixes to dialogue cleanup that would cause messages after : to be cut off. * init git repo if not exist * pull current branch * add 12 hours as option * world-state persist deactivated * install npm packages * fix typo * prompt tweaks * new screenshots and features updated * update screenshot
2024-01-19 11:47:38 +02:00
assert ensure_dialog_format(input) == expected
@pytest.mark.parametrize(
"input, expected, main_name",
[
("bob: says a sentence", "bob: says a sentence", "bob"),
(
"bob: says a sentence\nbob: says another sentence",
"bob: says a sentence\nsays another sentence",
"bob",
),
(
"bob: says a sentence with a colon: to explain something",
"bob: says a sentence with a colon: to explain something",
"bob",
),
(
"bob: i have a riddle for you, alice: the riddle",
"bob: i have a riddle for you, alice: the riddle",
"bob",
),
(
"bob: says something\nalice: says something else",
"bob: says something",
"bob",
),
("bob: says a sentence. then a", "bob: says a sentence.", "bob"),
(
"bob: first paragraph\n\nsecond paragraph",
"bob: first paragraph\n\nsecond paragraph",
"bob",
),
# movie script new speaker cutoff
(
"bob: says a sentence\n\nALICE\nsays something else",
"bob: says a sentence",
"bob",
),
],
)
Prep 0.17.0 (#48) * improve windows install script to check for compatible python versions, also work with multi version python installs * bunch of llm prompt templates * first gamestate directing impl * lower similarity threshold when checking for repetition in llm responses * tweaks to narrate after dialog prompt tweaks to extract character sheet prompt * set_context cmd * Xwin MoE * thematic generator for randomized content stimuli * add a memory query to extract character sheet * direct-scene prompt tweaks * conversation prompt tweaks * inline character creation from gameplay instruction template expose thematic generator to prompt templates * Mixtral Synthia-MoE * display prompt and response side by side * improve ensure_dialogue_format * prompt tweaks * prevent double passive narration in one round improvements to persist character logic * SlimOrca OpenBuddy * prompt tweaks * runpod status check wrapped in asyncio * generate_json_list creator agent action * limit conversation retries to 2 fix issue where REPETITION signal trigger would get sent with the prompt * smaller agent tweaks * thematic generator personality list thematic generator generate from sets of lists * adjust tests * mistral prompt adjustment * director: update content context * prompt adjustments * nous-hermes-2-yi dolphin-2.2-yo dolphin-2.6-mixtral * status messages * determine character goals generate json lists * fix error when chromadb add was called before db was ready (wait until the db is fully initiazed) * only strip extra spaces off of prompt textgenwebui: half temperature on -yi- models * prompt tweaks * more thematic generators * direct scene without character should just run the scene instructions if they exist * as_question_answer for query_scene * context_history revamp * Aurora-Nights MixtgralOrochi dolphin-2.7-mixtral nous-hermas-2-solar * remove old context_history calls * mv world_state.py to subdir FlatDolphinMaid Goliath Norobara Nous-Capybara * world state manager first progress * context db manager * fix issue with some clients not remembering context length settings after talemate restart * Sensualize-Solar * improve RAG prompt * conversation agent use [ as a stopping string since the new reinforcement messages use that * new method for RAG during conversation * mixtral_11bx2_moe * option to reset context db from manager ui * fix context db cleanup if scene is closed without saving * didnt mean to commit that * hide internal meta tags * keep track of manual context entries in scene save file so it can be rebuilt. * auto save auto progress quick settings hotbar options * manual mode actor dialogue tools refactor toolbar * narrate directed progress reorganiza narration tools into one cmd module * 0.17.0 * Mixtral_34Bx2 Sensualize-Mixtral openchat * fix save-as action * fix issue where too little context was joined in via RAG * context pins implementation * show active pins in world state component * pin condition eval and world state agent action config * Open_Gpt4 * summarization prompt improvements system prompt for summarization * guidance prompt for time passage narration * fix rerun for generic / unhandled messages * prompt fixes * summarization methods * prompt adjustments * world tools to hot bar ux tweaks * bagel-dpo * context state reinforcements support different insertion methods now (sequential, all context or conversation specific context) * first progress on world state reinforcement templating * Kunoichi * tweaks to update reinforcements prompt * world state templates progress * world state templates integration into main ux * fix issue where openai client wouldn't accept context length override * dont reconfigure client if no arguments are provided * pin condition prompt fixes world state apply template comman label set * world information / lore entries and reinforcement * show world entry states reinforcers in ux * gitignore * dynamic scenario generation progress * dynamic scenario experiment * gitignore * need to emit world state even if we dont run it during scene init * summarize and pin action * poetry relock * template question / attribute cannot be empty * fix issue with summarize and pin not respecting selected line * keep reinforcement messages in history, but keep the same one from stacking up * narrate query prompt more natural sounding response * manage pins from world entry editor * pin_only tag * ts aware summarize and pin pin text rendered to context with time label context reuse session id (this fixes issue of editing context entry and not saving the scene causing removal of context entry next time scene is loaded) * UX to add character state from template within the worldstate manager UX * move divider * handle agent emit error fix issue with state reinforcer validation * layout fixes in world state character panel physical health template added to example config * fix pin_only undefined error in world entry editor * laser-dolphin Noromaid-v0.4-Mixtral-Instruct * show state templates for world and players in favorite list fix applying world state template * refresh world entry list on state creation * changing a state from non-sequential to sequential should queue it as due * quicksettings to bar * fix error during memory db delete * status messages during scene load * removing a sequential state reinforcement should remove the reinforcement messages * Nous-Hermes-2-Mixtral * fix sync issue when editing character details through contextdb * immutable save property * enable director * update example config * enable director when loading a scene file that has instructions * fix more openai client funkyness with context size and losing model * iq dyn scenario prompt fixes * delay client save so that dragging the ctx slider doesnt send off a million requests default openai ctx to 8k * input disabled while clients active * declare event * narrate query prompt tweaks * fixes to dialogue cleanup that would cause messages after : to be cut off. * init git repo if not exist * pull current branch * add 12 hours as option * world-state persist deactivated * install npm packages * fix typo * prompt tweaks * new screenshots and features updated * update screenshot
2024-01-19 11:47:38 +02:00
def test_clean_dialogue(input, expected, main_name):
0.29.0 (#167) * set 0.29.0 * tweaks for dig layered history (wip) * move director agent to directory * relock * remove "none" from dig_layered_history response * determine character development * update character sheet from character development (wip) * org imports * alert outdated template overrides during startup * editor controls normalization of exposition * dialogue formatting refactor * fix narrator.clean_result forcing * regardless of editor fix exposition setting * move more of the dialogue cleanup logic into the editor fix exposition handlers * remove cruft * change ot normal selects and add some margin * move formatting option up * always strip partial sentences * separates exposition fixes from other dialogue cleanup operations, since we still want those * add novel formatting style * honor formatting config when no markers are supplied * fix issue where sometimes character message formatting would miss character name * director can now guide actors through scene analysis * style fixes * typo * select correct system message on direction type * prompt tweaks * disable by default * add support for dynamic instruction injection and include missing guide for internal note usage * change favicon and also indicate business through favicon * img * support xtc, dry and smoothing in text gen webui * prompt tweaks * support xtc, dry, smoothing in koboldcpp client * reorder * dry, xtc and smoothing factor exposed to tabby api client * urls to third party API documentation * remove bos token * add missing preset * focal * focal progress * focal progress and generated suggestions progress * fix issue with discard all suggestions * apply suggestions * move suggestion ux into the world state manager * support generation options for suggestion generation * unused import * refactor focal to json based approach * focal and character suggestion tweaks * rmeove cruft * remove cruft * relock * prompt tweaks * layout spacing updates * ux elements for removal of scenes from quick load menu * context investigation refactor WIP * context investigation refactor * context investigation refactor * context investigation refactor * cleanup * move scene analysis to summarizer agent * remove deprecated context investigation logic * context investigation refactor continued - split into separate file for easier maint * allow direct specification of response context length * context investigation and scene analyzation progress * change analysis length config to number * remove old dig-layered-history templates * summarizer - deep analysis is only available if there is layered history * move world_state agent to dedicated directory * remove unused imports * automatic character progression WIP * character suggestions progress * app busy flag based on agent business * indicate suggestions in world state overview * fix issue with user input cleanup * move conversation agent to a dedicated submodule * Response in action analyze_text_and_extract_context is too short #162 * move narrator agent to its own submodule * narrator improvements WIP * narration improvements WIP * fix issue with regen of character exit narration * narration improvements WIP * prompt tweaks * last_message_of_type can set max iterations * fix multiline parsing * prompt tweaks * director guide actors based of scene analysis * director guidance for actors * prompt tweaks * prompt tweaks * prompt tweaks * fix automatic character proposals not propagating to the ux * fix analysis length * support director guidance in legacy chat format * typo * prompt tweaks * prompt tweaks * error handling * length config * prompt tweaks * typo * remove cruft * prompt tweak * prompt tweak * time passage style changes * remove cruft * deep analysis context investigations honor call limit * refactor conversation agent long term memory to use new memory rag mixin - also streamline prompts * tweaks to RAG mixin agent config * fix narration highlighting * context investgiation fixes director narration guidance summarization tweaks * direactor guide narration progress context investigation fixes that would cause looping of investigations and failure to dig into the correct layers * prompt tweaks * summarization improvements * separate deep analysis chapter selection from analysis into its own prompt * character entry and exit * cache analysis per subtype and some narrator prompt tweaks * separate layered history logic into its own summarizer mixin and expose some additional options * scene can now set an overral writing style using writing style templates narrator option to enable writing style * narrate query writing style support * scene tools - narrator actions refactor to handler and own component * narrator query / look at narrations emitted as context investigation messages refactor context investigation messaage display scene message meta data object * include narrative direction * improve context investigation message prompt insert * reorg supported parameters * fix bug when no message history exists * WIP make regenerate work nicely with director guidance * WIP make regenerate work nicely with director guidance * regenerate conversation fixes * help text * ux tweaks * relock * turn off deep analysis and context investigations by default * long term memory options for director and summarizer * long term memory caching * fix summarization cache toggle not showing up in ux * ux tweaks * layered history summarization includes character information for mentioned characters * deepseek client added * Add fork button to narrator message * analyze and guidance support for time passage narration * cache based on message fingerprint instead of id * configurable system prompts WIP * configurable system prompts WIP * client overrides for system prompts wired to ux * system prompt overhaul * fix issue with unknown system prompt kind * add button to manually request dynamic choices from the director move the generate choices logic of the director agent to its own submodule * remove cruft * 30 may be too long and is causing the client to disappear temporarly * suppoert dynamic choice generate for non player characters * enable `actor` tab for player characters * creator agent now has access to rag tools improve acting instruction generation * client timeout fixes * fix issue where scene removal menu stayed open after remove * expose scene restore functionality to ux * create initial restore point * fix creator extra-context template * didn't mean to remove this * intro scene should be edited through world editor * fix alert * fix partial quotes regardless of editor setting director guidance for conversation reminds to put speech in quotes * fix @ instructions not being passed through to director guidance prompt * anthropic mode list updated * default off * cohere model list updated * reset actAs on next scene load * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * remove debug cruft * relock * docs on changing host / port * fix issue with narrator / director actiosn not available on fresh install * fix issue with long content classification determination result * take this reminder to put speech into quotes out for now, it seems to do more harm than good * fix some remaining issues with auto expositon fixes * prompt tweaks * prompt tweaks * fix issue during reload * expensive and warning ux passthrough for agent config * layered sumamry analysation defaults to on * what's new info block added * docs * what's new updated * remove old images * old img cleanup script * prompt tweaks * improve auto prompt template detection via huggingface * add gpt-4o-realtime-preview add gpt-4o-mini-realtime-preview * add o1 and o3-mini * fix o1 and o3 * fix o1 and o3 * more o1 / o3 fixes * o3 fixes
2025-02-01 17:44:06 +02:00
assert clean_dialogue(input, main_name) == expected
@pytest.mark.parametrize(
"input, expected",
[
('Hello how are you? "', "Hello how are you?"),
("Hello how are you? *", "Hello how are you?"),
("Hello how are you? {", "Hello how are you?"),
("Hello how are you? [", "Hello how are you?"),
("Hello how are you? (", "Hello how are you?"),
('"Hello how are you?"', '"Hello how are you?"'),
('"Hello how are you?" "', '"Hello how are you?"'),
('"Hello how are you?" *', '"Hello how are you?"'),
('"Hello how are you?" *"', '"Hello how are you?"'),
('*He says* "Hello how are you?"', '*He says* "Hello how are you?"'),
('*He says* "Hello how are you?" *', '*He says* "Hello how are you?"'),
('*He says* "Hello how are you?" *"', '*He says* "Hello how are you?"'),
("(Some thoughts)", "(Some thoughts)"),
("(Some thoughts) ", "(Some thoughts)"),
("(Some thoughts) (", "(Some thoughts)"),
("(Some thoughts) [", "(Some thoughts)"),
],
)
0.29.0 (#167) * set 0.29.0 * tweaks for dig layered history (wip) * move director agent to directory * relock * remove "none" from dig_layered_history response * determine character development * update character sheet from character development (wip) * org imports * alert outdated template overrides during startup * editor controls normalization of exposition * dialogue formatting refactor * fix narrator.clean_result forcing * regardless of editor fix exposition setting * move more of the dialogue cleanup logic into the editor fix exposition handlers * remove cruft * change ot normal selects and add some margin * move formatting option up * always strip partial sentences * separates exposition fixes from other dialogue cleanup operations, since we still want those * add novel formatting style * honor formatting config when no markers are supplied * fix issue where sometimes character message formatting would miss character name * director can now guide actors through scene analysis * style fixes * typo * select correct system message on direction type * prompt tweaks * disable by default * add support for dynamic instruction injection and include missing guide for internal note usage * change favicon and also indicate business through favicon * img * support xtc, dry and smoothing in text gen webui * prompt tweaks * support xtc, dry, smoothing in koboldcpp client * reorder * dry, xtc and smoothing factor exposed to tabby api client * urls to third party API documentation * remove bos token * add missing preset * focal * focal progress * focal progress and generated suggestions progress * fix issue with discard all suggestions * apply suggestions * move suggestion ux into the world state manager * support generation options for suggestion generation * unused import * refactor focal to json based approach * focal and character suggestion tweaks * rmeove cruft * remove cruft * relock * prompt tweaks * layout spacing updates * ux elements for removal of scenes from quick load menu * context investigation refactor WIP * context investigation refactor * context investigation refactor * context investigation refactor * cleanup * move scene analysis to summarizer agent * remove deprecated context investigation logic * context investigation refactor continued - split into separate file for easier maint * allow direct specification of response context length * context investigation and scene analyzation progress * change analysis length config to number * remove old dig-layered-history templates * summarizer - deep analysis is only available if there is layered history * move world_state agent to dedicated directory * remove unused imports * automatic character progression WIP * character suggestions progress * app busy flag based on agent business * indicate suggestions in world state overview * fix issue with user input cleanup * move conversation agent to a dedicated submodule * Response in action analyze_text_and_extract_context is too short #162 * move narrator agent to its own submodule * narrator improvements WIP * narration improvements WIP * fix issue with regen of character exit narration * narration improvements WIP * prompt tweaks * last_message_of_type can set max iterations * fix multiline parsing * prompt tweaks * director guide actors based of scene analysis * director guidance for actors * prompt tweaks * prompt tweaks * prompt tweaks * fix automatic character proposals not propagating to the ux * fix analysis length * support director guidance in legacy chat format * typo * prompt tweaks * prompt tweaks * error handling * length config * prompt tweaks * typo * remove cruft * prompt tweak * prompt tweak * time passage style changes * remove cruft * deep analysis context investigations honor call limit * refactor conversation agent long term memory to use new memory rag mixin - also streamline prompts * tweaks to RAG mixin agent config * fix narration highlighting * context investgiation fixes director narration guidance summarization tweaks * direactor guide narration progress context investigation fixes that would cause looping of investigations and failure to dig into the correct layers * prompt tweaks * summarization improvements * separate deep analysis chapter selection from analysis into its own prompt * character entry and exit * cache analysis per subtype and some narrator prompt tweaks * separate layered history logic into its own summarizer mixin and expose some additional options * scene can now set an overral writing style using writing style templates narrator option to enable writing style * narrate query writing style support * scene tools - narrator actions refactor to handler and own component * narrator query / look at narrations emitted as context investigation messages refactor context investigation messaage display scene message meta data object * include narrative direction * improve context investigation message prompt insert * reorg supported parameters * fix bug when no message history exists * WIP make regenerate work nicely with director guidance * WIP make regenerate work nicely with director guidance * regenerate conversation fixes * help text * ux tweaks * relock * turn off deep analysis and context investigations by default * long term memory options for director and summarizer * long term memory caching * fix summarization cache toggle not showing up in ux * ux tweaks * layered history summarization includes character information for mentioned characters * deepseek client added * Add fork button to narrator message * analyze and guidance support for time passage narration * cache based on message fingerprint instead of id * configurable system prompts WIP * configurable system prompts WIP * client overrides for system prompts wired to ux * system prompt overhaul * fix issue with unknown system prompt kind * add button to manually request dynamic choices from the director move the generate choices logic of the director agent to its own submodule * remove cruft * 30 may be too long and is causing the client to disappear temporarly * suppoert dynamic choice generate for non player characters * enable `actor` tab for player characters * creator agent now has access to rag tools improve acting instruction generation * client timeout fixes * fix issue where scene removal menu stayed open after remove * expose scene restore functionality to ux * create initial restore point * fix creator extra-context template * didn't mean to remove this * intro scene should be edited through world editor * fix alert * fix partial quotes regardless of editor setting director guidance for conversation reminds to put speech in quotes * fix @ instructions not being passed through to director guidance prompt * anthropic mode list updated * default off * cohere model list updated * reset actAs on next scene load * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * remove debug cruft * relock * docs on changing host / port * fix issue with narrator / director actiosn not available on fresh install * fix issue with long content classification determination result * take this reminder to put speech into quotes out for now, it seems to do more harm than good * fix some remaining issues with auto expositon fixes * prompt tweaks * prompt tweaks * fix issue during reload * expensive and warning ux passthrough for agent config * layered sumamry analysation defaults to on * what's new info block added * docs * what's new updated * remove old images * old img cleanup script * prompt tweaks * improve auto prompt template detection via huggingface * add gpt-4o-realtime-preview add gpt-4o-mini-realtime-preview * add o1 and o3-mini * fix o1 and o3 * fix o1 and o3 * more o1 / o3 fixes * o3 fixes
2025-02-01 17:44:06 +02:00
def test_remove_trailing_markers(input, expected):
0.30.0 (#184) * pytorch update * github workflow for tests * tests set up config * tests download nltk punkt * punkt_tab * fix world state not updating on new initial scene load * fix new character creation from scene tools * py 312 py 313 support remove unreliant cuda detection and just lock poetry with cuda * fix tests * dont auto install cuda * remove unused StrEnum import * separate cuda install * fix auto progress OFF no longer working * fix debug logging options not sticking * disable revision during image prompt generation * prompt tweaks * prompt tweaks * fix some issues with directed character creation * tweak the continue generation button so its less prone to pop into a new line on itsown * fix context db filter field layout * handle error when trying to regnerate passthrough narrator message * prompt tweaks * increase auto direct evaluation length * fix node library on windows * auto direct eval tweaks * prompt tweaks * prompt tweaks * allow updationg of scene phase through director console * add generate action to director console phase intent text fields * prompt tweaks * track iteration count in scene loop always yield to user at initial start / load of a scene * fix issue with Split and Join nodes when passed \n as delimiter * sim suite only generate auto direct requirements if auto direct is enabled sim suite fix issues with title generation * autocomplete button disable until there is text to autcomplete * update installation docs * update scenario tools docs * docs * writing style phrase detection * typo * docs * fix issue where deleting an applied preset group would prevent selection of a different preset group in the affected client * fix @-Instruction is broken when using apostrophes * editor never attempt to fix exposition on user input if input starts with command characters @, ! or / * prompt tweaks * editor revision: automatic revision setting, prompt tweaks, docs * missing files * fix issue where narration responses starting with # would result in empty messages * prompt tweaks * fix issue with autocomplete not working at the beginning of a scene * fix issues where cached guidance would result in no guidance * editor revision analysis now has access to scene analysis and director guidance if it exists * fix issue where all nodes in the node editor would be locked on winsows OS * add `scene/SetIntroducation` node * fix issue where generating narration in a scene with zero characters would always come back blank * SceneIntroduction node state output fixed * node editor docs progress * fix issue with loading scene from file upload no longer working * better handling of what to do when there are no characters in a scene and no default character is defined * typo * silence trigger game loop debug message * docs * GenerateThematicList node * docs * docs * stubs * allow creation of module from existing nodes * move function into plugin * separate graph export functions into own .js file * group from selected nodes * remove debug output * tweak create module dialog * docs * docs * graph tests need to assume auto_progres True * add ModuleProperty node * fix some issues in the module creation modal when extending or copying a module * include module name in module deletion confirm dialog * fix node module copy not setting updated registry * module property name output * docs * docs * initializing a scene from a character card will no longer break the node editor * docs * when greeting text and intro do not match, do the greeting text first. * intro is set during card import, there is no need to ever emit character greetings in addition to the intro, its not really something that matches talemate's design philsophy at this point * docs * dynamic premise modules * tweaks * propagate module level property defaults to node * docs * fix issue where the default character would get added to scenes during load even though there already was a player character * prompt tweaks * tweaks to generate-premise module * docs * infinity quest dynamic story v2 * tweaks limits * fix line endings * prompt tweaks * fix some issues with node property editing * formatting * prompt tweaks * group and comment * add talemate tint node style fix gap in nodes when there are no sockets * node style fixes * docs * docs * icon for swtich nodes * conditional emit status node * don't reset dynamic premise * dynamic premise tweaks * dynamic premis status messages * fix issue with Input value error node * validate that topic is specified * fix issue where cancelling a generation triggered during scene loop init would cause the loop to reinitialize * docs * node error handling improvements * docs * better error handling in generate premise module * a connected socket should always override a property of the same value even if the socket connection is not resolved * dynamic premise expose intro length property * fix some issues with node module creation and add registry path validation * correctly title creative loop module so it can be copied * remove debug message * rename to dynamic storyline for clarity and so it doesn't collide with tutorial * import dynanimc storyline node * docs * gracefully handle a node missing during graph load * docs * make agent list a bit more compact * disable node property editing in inherited nodes * rename editor revision events so they are inline with the other agent events * support instruction injection for director.generate_choices action * normalize dynamic instructions * fix director guidance dynamic instructions * docs * generate choices event add choices property * prompt tweaks * add dynamic instruction node * prompt tweak * fix issue where some events could not be hooked into through event node modules * docs * clean response node * docs * docs * docs * module library tweaks * fix some issues with act-as selection * dont allow creation of new modules until scene has been saved at least once * public node modules dir * sim suite module styles * remove debug messages * fix default node titles * fix number input vlaidation in math nodes * context awareness in contextual generate now includes character info * fix dupe id warnings * alt drag to clone multiple nodes * alt drag to clone multiple nodes * docs * docs * fix issue where some scene modules could leak across scenes * dynamic instructions already included through extra context * prompt tweaks * update defaults * docs * make list init from json * socs * fix issue where not all field definitions would get sent * docs * fix issue causing deep analysis to loop * case insentive regex matching * prompt tweaks * fix node title * fix size issue in scene view when node editor was open on smaller resolutions * fix issue with autocomplete sometime loosing markup * add claude 4 * make director guidance and actor instructions available to autocomplete prompt * fix trim node handling of \n * extract node * extract node trim property * remover cruft * charactermessage node only set character if not already part of message prefix * editor revision unslop mode * fix search scenes showing node module files * prompt tweaks * unslop support unwanted phrase detection * define bad_prose * </FIX> seems to get ommitted a lot so lets handle it * cleanup * return on no issues * fix some issues with character creation * fix some character creation issues * prompt tweaks * contewxtual generate and autocomplete signals added * prefix revision_ * use uuidv4 which is already installed and doesnt come with compatibility issues * editor revision support for contextual generations normalize some event objects * add template picker to worldstate character creation interface * prompt tweaks * dont unslop scene intent or story intent generation * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * fix issue of conversation losing edits through signals * support revisions for world state entry generation * task_instructions * dont show rewrite specific options if unslop method is selected * docs * fix issue with setting locked save file when auto saving was turned on * don't trigger player_turn_start in creative mode * better check for when to fire player_turn_start and when not * node editor crash course fixes * docs * fix issue where sometimes wrong system prompt was selected * add world context to contextual generate node * fix node dragging issue when cloning multiple nodes * support editor revision for summarization generation * summarization support dynamic instructions * dedicated template for summary unslop * pass summarization_history to template vars * prompt tweaks * prompt tweaks * not sure how this got blanked * wording * wording * only display debug log if TALEMATE_DEBUG=1 * fix syntax * fix syntax * remove unused cruft * start-debug * log message cleanup * docs * tweak defaults * sim suite polish * remove unused images * add writing style instructions to revision prompts * missing endif tag * prompt tweaks * prompt tweaks * prompt tweaks * use app-busy * prompt tweaks * update readme and screenshots wording wording * add discord link
2025-06-03 12:26:12 +03:00
assert remove_trailing_markers(input) == expected
@pytest.mark.parametrize(
"input, anchor_length, expected_non_anchor, expected_anchor",
[
("", 10, "", ""),
("Hello", 10, "", "Hello"),
("This is a short example", 10, "This is", "a short example"),
("One two three four", 4, "One two", "three four"),
(
"This is a longer example with more than ten words to test the anchor functionality",
10,
"This is a longer example",
"with more than ten words to test the anchor functionality",
),
(
"One two three four five six seven eight nine ten",
10,
"One two three four five",
"six seven eight nine ten",
),
("Two words", 10, "Two", "words"),
("One Two Three", 3, "One", "Two Three"),
],
)
0.30.0 (#184) * pytorch update * github workflow for tests * tests set up config * tests download nltk punkt * punkt_tab * fix world state not updating on new initial scene load * fix new character creation from scene tools * py 312 py 313 support remove unreliant cuda detection and just lock poetry with cuda * fix tests * dont auto install cuda * remove unused StrEnum import * separate cuda install * fix auto progress OFF no longer working * fix debug logging options not sticking * disable revision during image prompt generation * prompt tweaks * prompt tweaks * fix some issues with directed character creation * tweak the continue generation button so its less prone to pop into a new line on itsown * fix context db filter field layout * handle error when trying to regnerate passthrough narrator message * prompt tweaks * increase auto direct evaluation length * fix node library on windows * auto direct eval tweaks * prompt tweaks * prompt tweaks * allow updationg of scene phase through director console * add generate action to director console phase intent text fields * prompt tweaks * track iteration count in scene loop always yield to user at initial start / load of a scene * fix issue with Split and Join nodes when passed \n as delimiter * sim suite only generate auto direct requirements if auto direct is enabled sim suite fix issues with title generation * autocomplete button disable until there is text to autcomplete * update installation docs * update scenario tools docs * docs * writing style phrase detection * typo * docs * fix issue where deleting an applied preset group would prevent selection of a different preset group in the affected client * fix @-Instruction is broken when using apostrophes * editor never attempt to fix exposition on user input if input starts with command characters @, ! or / * prompt tweaks * editor revision: automatic revision setting, prompt tweaks, docs * missing files * fix issue where narration responses starting with # would result in empty messages * prompt tweaks * fix issue with autocomplete not working at the beginning of a scene * fix issues where cached guidance would result in no guidance * editor revision analysis now has access to scene analysis and director guidance if it exists * fix issue where all nodes in the node editor would be locked on winsows OS * add `scene/SetIntroducation` node * fix issue where generating narration in a scene with zero characters would always come back blank * SceneIntroduction node state output fixed * node editor docs progress * fix issue with loading scene from file upload no longer working * better handling of what to do when there are no characters in a scene and no default character is defined * typo * silence trigger game loop debug message * docs * GenerateThematicList node * docs * docs * stubs * allow creation of module from existing nodes * move function into plugin * separate graph export functions into own .js file * group from selected nodes * remove debug output * tweak create module dialog * docs * docs * graph tests need to assume auto_progres True * add ModuleProperty node * fix some issues in the module creation modal when extending or copying a module * include module name in module deletion confirm dialog * fix node module copy not setting updated registry * module property name output * docs * docs * initializing a scene from a character card will no longer break the node editor * docs * when greeting text and intro do not match, do the greeting text first. * intro is set during card import, there is no need to ever emit character greetings in addition to the intro, its not really something that matches talemate's design philsophy at this point * docs * dynamic premise modules * tweaks * propagate module level property defaults to node * docs * fix issue where the default character would get added to scenes during load even though there already was a player character * prompt tweaks * tweaks to generate-premise module * docs * infinity quest dynamic story v2 * tweaks limits * fix line endings * prompt tweaks * fix some issues with node property editing * formatting * prompt tweaks * group and comment * add talemate tint node style fix gap in nodes when there are no sockets * node style fixes * docs * docs * icon for swtich nodes * conditional emit status node * don't reset dynamic premise * dynamic premise tweaks * dynamic premis status messages * fix issue with Input value error node * validate that topic is specified * fix issue where cancelling a generation triggered during scene loop init would cause the loop to reinitialize * docs * node error handling improvements * docs * better error handling in generate premise module * a connected socket should always override a property of the same value even if the socket connection is not resolved * dynamic premise expose intro length property * fix some issues with node module creation and add registry path validation * correctly title creative loop module so it can be copied * remove debug message * rename to dynamic storyline for clarity and so it doesn't collide with tutorial * import dynanimc storyline node * docs * gracefully handle a node missing during graph load * docs * make agent list a bit more compact * disable node property editing in inherited nodes * rename editor revision events so they are inline with the other agent events * support instruction injection for director.generate_choices action * normalize dynamic instructions * fix director guidance dynamic instructions * docs * generate choices event add choices property * prompt tweaks * add dynamic instruction node * prompt tweak * fix issue where some events could not be hooked into through event node modules * docs * clean response node * docs * docs * docs * module library tweaks * fix some issues with act-as selection * dont allow creation of new modules until scene has been saved at least once * public node modules dir * sim suite module styles * remove debug messages * fix default node titles * fix number input vlaidation in math nodes * context awareness in contextual generate now includes character info * fix dupe id warnings * alt drag to clone multiple nodes * alt drag to clone multiple nodes * docs * docs * fix issue where some scene modules could leak across scenes * dynamic instructions already included through extra context * prompt tweaks * update defaults * docs * make list init from json * socs * fix issue where not all field definitions would get sent * docs * fix issue causing deep analysis to loop * case insentive regex matching * prompt tweaks * fix node title * fix size issue in scene view when node editor was open on smaller resolutions * fix issue with autocomplete sometime loosing markup * add claude 4 * make director guidance and actor instructions available to autocomplete prompt * fix trim node handling of \n * extract node * extract node trim property * remover cruft * charactermessage node only set character if not already part of message prefix * editor revision unslop mode * fix search scenes showing node module files * prompt tweaks * unslop support unwanted phrase detection * define bad_prose * </FIX> seems to get ommitted a lot so lets handle it * cleanup * return on no issues * fix some issues with character creation * fix some character creation issues * prompt tweaks * contewxtual generate and autocomplete signals added * prefix revision_ * use uuidv4 which is already installed and doesnt come with compatibility issues * editor revision support for contextual generations normalize some event objects * add template picker to worldstate character creation interface * prompt tweaks * dont unslop scene intent or story intent generation * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * fix issue of conversation losing edits through signals * support revisions for world state entry generation * task_instructions * dont show rewrite specific options if unslop method is selected * docs * fix issue with setting locked save file when auto saving was turned on * don't trigger player_turn_start in creative mode * better check for when to fire player_turn_start and when not * node editor crash course fixes * docs * fix issue where sometimes wrong system prompt was selected * add world context to contextual generate node * fix node dragging issue when cloning multiple nodes * support editor revision for summarization generation * summarization support dynamic instructions * dedicated template for summary unslop * pass summarization_history to template vars * prompt tweaks * prompt tweaks * not sure how this got blanked * wording * wording * only display debug log if TALEMATE_DEBUG=1 * fix syntax * fix syntax * remove unused cruft * start-debug * log message cleanup * docs * tweak defaults * sim suite polish * remove unused images * add writing style instructions to revision prompts * missing endif tag * prompt tweaks * prompt tweaks * prompt tweaks * use app-busy * prompt tweaks * update readme and screenshots wording wording * add discord link
2025-06-03 12:26:12 +03:00
def test_split_anchor_text(input, anchor_length, expected_non_anchor, expected_anchor):
from talemate.util.dialogue import split_anchor_text
0.30.0 (#184) * pytorch update * github workflow for tests * tests set up config * tests download nltk punkt * punkt_tab * fix world state not updating on new initial scene load * fix new character creation from scene tools * py 312 py 313 support remove unreliant cuda detection and just lock poetry with cuda * fix tests * dont auto install cuda * remove unused StrEnum import * separate cuda install * fix auto progress OFF no longer working * fix debug logging options not sticking * disable revision during image prompt generation * prompt tweaks * prompt tweaks * fix some issues with directed character creation * tweak the continue generation button so its less prone to pop into a new line on itsown * fix context db filter field layout * handle error when trying to regnerate passthrough narrator message * prompt tweaks * increase auto direct evaluation length * fix node library on windows * auto direct eval tweaks * prompt tweaks * prompt tweaks * allow updationg of scene phase through director console * add generate action to director console phase intent text fields * prompt tweaks * track iteration count in scene loop always yield to user at initial start / load of a scene * fix issue with Split and Join nodes when passed \n as delimiter * sim suite only generate auto direct requirements if auto direct is enabled sim suite fix issues with title generation * autocomplete button disable until there is text to autcomplete * update installation docs * update scenario tools docs * docs * writing style phrase detection * typo * docs * fix issue where deleting an applied preset group would prevent selection of a different preset group in the affected client * fix @-Instruction is broken when using apostrophes * editor never attempt to fix exposition on user input if input starts with command characters @, ! or / * prompt tweaks * editor revision: automatic revision setting, prompt tweaks, docs * missing files * fix issue where narration responses starting with # would result in empty messages * prompt tweaks * fix issue with autocomplete not working at the beginning of a scene * fix issues where cached guidance would result in no guidance * editor revision analysis now has access to scene analysis and director guidance if it exists * fix issue where all nodes in the node editor would be locked on winsows OS * add `scene/SetIntroducation` node * fix issue where generating narration in a scene with zero characters would always come back blank * SceneIntroduction node state output fixed * node editor docs progress * fix issue with loading scene from file upload no longer working * better handling of what to do when there are no characters in a scene and no default character is defined * typo * silence trigger game loop debug message * docs * GenerateThematicList node * docs * docs * stubs * allow creation of module from existing nodes * move function into plugin * separate graph export functions into own .js file * group from selected nodes * remove debug output * tweak create module dialog * docs * docs * graph tests need to assume auto_progres True * add ModuleProperty node * fix some issues in the module creation modal when extending or copying a module * include module name in module deletion confirm dialog * fix node module copy not setting updated registry * module property name output * docs * docs * initializing a scene from a character card will no longer break the node editor * docs * when greeting text and intro do not match, do the greeting text first. * intro is set during card import, there is no need to ever emit character greetings in addition to the intro, its not really something that matches talemate's design philsophy at this point * docs * dynamic premise modules * tweaks * propagate module level property defaults to node * docs * fix issue where the default character would get added to scenes during load even though there already was a player character * prompt tweaks * tweaks to generate-premise module * docs * infinity quest dynamic story v2 * tweaks limits * fix line endings * prompt tweaks * fix some issues with node property editing * formatting * prompt tweaks * group and comment * add talemate tint node style fix gap in nodes when there are no sockets * node style fixes * docs * docs * icon for swtich nodes * conditional emit status node * don't reset dynamic premise * dynamic premise tweaks * dynamic premis status messages * fix issue with Input value error node * validate that topic is specified * fix issue where cancelling a generation triggered during scene loop init would cause the loop to reinitialize * docs * node error handling improvements * docs * better error handling in generate premise module * a connected socket should always override a property of the same value even if the socket connection is not resolved * dynamic premise expose intro length property * fix some issues with node module creation and add registry path validation * correctly title creative loop module so it can be copied * remove debug message * rename to dynamic storyline for clarity and so it doesn't collide with tutorial * import dynanimc storyline node * docs * gracefully handle a node missing during graph load * docs * make agent list a bit more compact * disable node property editing in inherited nodes * rename editor revision events so they are inline with the other agent events * support instruction injection for director.generate_choices action * normalize dynamic instructions * fix director guidance dynamic instructions * docs * generate choices event add choices property * prompt tweaks * add dynamic instruction node * prompt tweak * fix issue where some events could not be hooked into through event node modules * docs * clean response node * docs * docs * docs * module library tweaks * fix some issues with act-as selection * dont allow creation of new modules until scene has been saved at least once * public node modules dir * sim suite module styles * remove debug messages * fix default node titles * fix number input vlaidation in math nodes * context awareness in contextual generate now includes character info * fix dupe id warnings * alt drag to clone multiple nodes * alt drag to clone multiple nodes * docs * docs * fix issue where some scene modules could leak across scenes * dynamic instructions already included through extra context * prompt tweaks * update defaults * docs * make list init from json * socs * fix issue where not all field definitions would get sent * docs * fix issue causing deep analysis to loop * case insentive regex matching * prompt tweaks * fix node title * fix size issue in scene view when node editor was open on smaller resolutions * fix issue with autocomplete sometime loosing markup * add claude 4 * make director guidance and actor instructions available to autocomplete prompt * fix trim node handling of \n * extract node * extract node trim property * remover cruft * charactermessage node only set character if not already part of message prefix * editor revision unslop mode * fix search scenes showing node module files * prompt tweaks * unslop support unwanted phrase detection * define bad_prose * </FIX> seems to get ommitted a lot so lets handle it * cleanup * return on no issues * fix some issues with character creation * fix some character creation issues * prompt tweaks * contewxtual generate and autocomplete signals added * prefix revision_ * use uuidv4 which is already installed and doesnt come with compatibility issues * editor revision support for contextual generations normalize some event objects * add template picker to worldstate character creation interface * prompt tweaks * dont unslop scene intent or story intent generation * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * prompt tweaks * fix issue of conversation losing edits through signals * support revisions for world state entry generation * task_instructions * dont show rewrite specific options if unslop method is selected * docs * fix issue with setting locked save file when auto saving was turned on * don't trigger player_turn_start in creative mode * better check for when to fire player_turn_start and when not * node editor crash course fixes * docs * fix issue where sometimes wrong system prompt was selected * add world context to contextual generate node * fix node dragging issue when cloning multiple nodes * support editor revision for summarization generation * summarization support dynamic instructions * dedicated template for summary unslop * pass summarization_history to template vars * prompt tweaks * prompt tweaks * not sure how this got blanked * wording * wording * only display debug log if TALEMATE_DEBUG=1 * fix syntax * fix syntax * remove unused cruft * start-debug * log message cleanup * docs * tweak defaults * sim suite polish * remove unused images * add writing style instructions to revision prompts * missing endif tag * prompt tweaks * prompt tweaks * prompt tweaks * use app-busy * prompt tweaks * update readme and screenshots wording wording * add discord link
2025-06-03 12:26:12 +03:00
non_anchor, anchor = split_anchor_text(input, anchor_length)
assert non_anchor == expected_non_anchor
assert anchor == expected_anchor
0.32.0 (#208) * separate other tts apis and improve chunking * move old tts config to voice agent config and implement config widget ux elements for table editing * elevenlabs updated to use their client and expose model selection * linting * separate character class into character.pt and start on voice routing * linting * tts hot swapping and chunking improvements * linting * add support for piper-tts * update gitignore * linting * support google tts fix issue where quick_toggle agent config didnt work on standard config items * linting * only show agent quick toggles if the agent is enabled * change elevenlabs to use a locally maintained voice list * tts generate before / after events * voice library refactor * linting * update openai model and voices * tweak configs * voice library ux * linting * add support for kokoro tts * fix add / remove voice * voice library tags * linting * linting * tts api status * api infos and add more kokoro voices * allow voice testing before saving a new voice * tweaks to voice library ux and some api info text * linting * voice mixer * polish * voice files go into /tts instead of templates/voice * change default narrator voice * xtts confirmation note * character voice select * koboldai format template * polish * skip empty chunks * change default voice * replace em-dash with normal dash * adjust limit * replace libebreaks * chunk cleanup for whitespace * info updated * remove invalid endif tag * sort voices by ready api * Character hashable type * clarify set_simulated_environment use to avoid unwanted character deactivated * allow manual generation of tts and fix assorted issues with tts * tts websocket handler router renamed * voice mixer: when there are only 2 voices auto adjust the other weight as needed * separate persist character functions into own mixin * auto assign voices * fix chara load and auto assign voice during chara load * smart speaker separation * tts speaker separation config * generate tts for intro text * fix prompting issues with anthropic, google and openrouter clients * decensor flag off again * only to ai assisted voice markup on narrator messages * openrouter provider configuration * linting * improved sound controls * add support for chatterbox * fix info * chatterbox dependencies * remove piper and xtts2 * linting * voice params * linting * tts model overrides and move tts info to tab * reorg toolbar * allow overriding of test text * more tts fixes, apply intensity, chatterbox voices * confirm voice delete * lintinG * groq updates * reorg decorators * tts fixes * cancelable audio queue * voice library uploads * scene voice library * Config refactor (#13) * config refactor progres * config nuke continues * fix system prompts * linting * client fun * client config refactor * fix kcpp auto embedding selection * linting * fix proxy config * remove cruft * fix remaining client bugs from config refactor always use get_config(), dont keep an instance reference * support for reasoning models * more reasoning tweaks * only allow one frontend to connect at a time * fix tests * relock * relock * more client adjustments * pattern prefill * some tts agent fixes * fix ai assist cond * tts nodes * fix config retrieval * assign voice node and fixes * sim suite char gen assign voice * fix voice assign template to consider used voices * get rid of auto break repetition which wasn't working right for a while anyhow * linting * generate tts node as string node * linting * voice change on character event * tweak chatterbox max length * koboldai default template * linting * fix saving of existing voice * relock * adjust params of eva default voice * f5tts support * f5tts samples * f5tts support * f5tts tweaks * chunk size per tts api and reorg defaul f5tts voices * chatterbox default voice reog to match f5-tts default voices * voice library ux polish pass * cleanup * f5-tts tweaks * missing samples * get rid of old save cmd * add chatterbox and f5tts * housekeeping * fix some issues with world entry editing * remove cruft * replace exclamation marks * fix save immutable check * fix replace_exclamation_marks * better error handling in websocket plugins and fix issue with saves * agent config save on dialog close * ctrl click to disable / enable agents * fix quick config * allow modifying response size of focal requests * sim suite set goal always sets story intent, encourage calling of set goal during simulation start * allow setting of model * voice param tweaks * tts tweaks * fix character card load * fix note_on_value * add mixed speaker_separation mode * indicate which message the audio is for and provide way to stop audio from the message * fix issue with some tts generation failing * linting * fix speaker separate modes * bad idea * linting * refactor speaker separation prompt * add kimi think pattern * fix issue with unwanted cover image replacemenT * no scene analysis for visual promp generation (for now) * linting * tts for context investigation messages * prompt tweaks * tweak intro * fix intro text tts not auto playing sometimes * consider narrator voice when assigning voice tro a character * allow director log messages to go only into the director console * linting * startup performance fixes * init time * linting * only show audio control for messagews taht can have it * always create story intent and dont override existing saves during character card load * fix history check in dynamic story line node add HasHistory node * linting * fix intro message not having speaker separation * voice library character manager * sequantial and cancelable auto assign all * linting * fix generation cancel handling * tooltips * fix auto assign voice from scene voices * polish * kokoro does not like lazy import * update info text * complete scene export / import * linting * wording * remove cruft * fix story intent generation during character card import * fix generation cancelled emit status inf loop * prompt tweak * reasoning quick toggle, reasoning token slider, tooltips * improved reasoning pattern handling * fix indirect coercion response parsing * fix streaming issue * response length instructions * more robust streaming * adjust default * adjust formatting * litning * remove debug output * director console log function calls * install cuda script updated * linting * add another step * adjust default * update dialogue examples * fix voice selection issues * what's happening here * third time's the charm? * Vite migration (#207) * add vite config * replace babel, webpack, vue-cli deps with vite, switch to esm modules, separate eslint config * change process.env to import.meta.env * update index.html for vite and move to root * update docs for vite * remove vue cli config * update example env with vite * bump frontend deps after rebase to 32.0 --------- Co-authored-by: pax-co <Pax_801@proton.me> * properly referencer data type * what's new * better indication of dialogue example supporting multiple lines, improve dialogue example display * fix potential issue with cached scene anlysis being reused when it shouldn't * fix character creation issues with player character toggle * fix issue where editing a message would sometimes lose parts of the message * fix slider ux thumb labels (vuetify update) * relock * narrative conversation format * remove planning step * linting * tweaks * don't overthink * update dialogue examples and intro * dont dictate response length instructions when data structures are expected * prompt tweaks * prompt tweaks * linting * fix edit message not handling : well * prompt tweaks * fix tests * fix manual revision when character message was generated in new narrative mode * fix issue with message editing * Docker packages relese (#204) * add CI workflow for Docker image build and MkDocs deployment * rename CI workflow from 'ci' to 'package' * refactor CI workflow: consolidate container build and documentation deployment into a single file * fix: correct indentation for permissions in CI workflow * fix: correct indentation for steps in deploy-docs job in CI workflow * build both cpu and cuda image * docs * docs * expose writing style during state reinforcement * prompt tweaks * test container build * test container image * update docker compose * docs * test-container-build * test container build * test container build * update docker build workflows * fix guidance prompt prefix not being dropped * mount tts dir * add gpt-5 * remove debug output * docs * openai auto toggle reasoning based on model selection * linting --------- Co-authored-by: pax-co <123330830+pax-co@users.noreply.github.com> Co-authored-by: pax-co <Pax_801@proton.me> Co-authored-by: Luis Alexandre Deschamps Brandão <brandao_luis@yahoo.com>
2025-08-08 13:56:29 +03:00
@pytest.mark.parametrize(
"input, expected",
[
# Empty text
("", []),
# Only dialogue
('"Hello world"', [{"text": '"Hello world"', "type": "dialogue"}]),
# Only exposition
("This is exposition", [{"text": "This is exposition", "type": "exposition"}]),
# Simple mixed case
(
'He said "Hello" to her',
[
{"text": "He said ", "type": "exposition"},
{"text": '"Hello"', "type": "dialogue"},
{"text": " to her", "type": "exposition"},
],
),
# Multiple dialogues
(
'"Hi" she said "Bye"',
[
{"text": '"Hi"', "type": "dialogue"},
{"text": " she said ", "type": "exposition"},
{"text": '"Bye"', "type": "dialogue"},
],
),
# Exposition with asterisks (should be treated as exposition)
(
'*He walks* "Hello" *He smiles*',
[
{"text": "*He walks* ", "type": "exposition"},
{"text": '"Hello"', "type": "dialogue"},
{"text": " *He smiles*", "type": "exposition"},
],
),
# Dialogue spanning multiple lines
(
'He said "Hello\nHow are you?" nicely',
[
{"text": "He said ", "type": "exposition"},
{"text": '"Hello\nHow are you?"', "type": "dialogue"},
{"text": " nicely", "type": "exposition"},
],
),
# Complex mixed content
(
'The man said "I am fine" and *walked away* before saying "Goodbye"',
[
{"text": "The man said ", "type": "exposition"},
{"text": '"I am fine"', "type": "dialogue"},
{"text": " and *walked away* before saying ", "type": "exposition"},
{"text": '"Goodbye"', "type": "dialogue"},
],
),
# Unmatched quotes (last quote doesn't close)
(
'He said "Hello',
[
{"text": "He said ", "type": "exposition"},
{"text": '"Hello', "type": "dialogue"},
],
),
# Empty dialogue
(
'Before "" after',
[
{"text": "Before ", "type": "exposition"},
{"text": '""', "type": "dialogue"},
{"text": " after", "type": "exposition"},
],
),
# Multiple quotes in exposition (edge case)
(
'She thought about the word "love" and "hate" often',
[
{"text": "She thought about the word ", "type": "exposition"},
{"text": '"love"', "type": "dialogue"},
{"text": " and ", "type": "exposition"},
{"text": '"hate"', "type": "dialogue"},
{"text": " often", "type": "exposition"},
],
),
# Nested quotes scenario (treating inner quotes as part of dialogue)
(
"He said \"She told me 'hi' yesterday\"",
[
{"text": "He said ", "type": "exposition"},
{"text": "\"She told me 'hi' yesterday\"", "type": "dialogue"},
],
),
# Just quotes
('""', [{"text": '""', "type": "dialogue"}]),
# Quotes at start and end
(
'"Start" middle "End"',
[
{"text": '"Start"', "type": "dialogue"},
{"text": " middle ", "type": "exposition"},
{"text": '"End"', "type": "dialogue"},
],
),
# Single quote (unmatched)
('"', [{"text": '"', "type": "dialogue"}]),
# Text ending with quote start
(
'Hello "',
[
{"text": "Hello ", "type": "exposition"},
{"text": '"', "type": "dialogue"},
],
),
],
)
def test_separate_dialogue_from_exposition(input, expected):
from talemate.util.dialogue import separate_dialogue_from_exposition
result = separate_dialogue_from_exposition(input)
# Convert result to list of dicts for easier comparison
result_dicts = [{"text": chunk.text, "type": chunk.type} for chunk in result]
assert result_dicts == expected
# New tests to validate speaker identification within dialogue chunks
@pytest.mark.parametrize(
"input, expected",
[
# Single dialogue with speaker
(
'"{John}I am leaving now."',
[
{"text": '"I am leaving now."', "type": "dialogue", "speaker": "John"},
],
),
# Dialogue embedded within exposition, with speaker
(
'She whispered "{Alice}Be careful" before disappearing.',
[
{"text": "She whispered ", "type": "exposition", "speaker": None},
{"text": '"Be careful"', "type": "dialogue", "speaker": "Alice"},
{
"text": " before disappearing.",
"type": "exposition",
"speaker": None,
},
],
),
# Multiple dialogues with different speakers
(
'"{Bob}Hi" she replied "{Carol}Hello"',
[
{"text": '"Hi"', "type": "dialogue", "speaker": "Bob"},
{"text": " she replied ", "type": "exposition", "speaker": None},
{"text": '"Hello"', "type": "dialogue", "speaker": "Carol"},
],
),
# Prev speaker
(
'"{Bob}First dialog" some exposition "Second dialog" some more expostition "{Sarah}Third dialog"',
[
{"text": '"First dialog"', "type": "dialogue", "speaker": "Bob"},
{"text": " some exposition ", "type": "exposition", "speaker": None},
{"text": '"Second dialog"', "type": "dialogue", "speaker": "Bob"},
{
"text": " some more expostition ",
"type": "exposition",
"speaker": None,
},
{"text": '"Third dialog"', "type": "dialogue", "speaker": "Sarah"},
],
),
],
)
def test_separate_dialogue_from_exposition_speaker(input, expected):
"""Ensure that speakers wrapped in curly-braces at the start of a dialogue segment
are correctly extracted into the `speaker` field and removed from the `text`."""
from talemate.util.dialogue import separate_dialogue_from_exposition
result = separate_dialogue_from_exposition(input)
# Convert result to list of dicts including the speaker field for comparison
result_dicts = [
{"text": chunk.text, "type": chunk.type, "speaker": chunk.speaker}
for chunk in result
]
assert result_dicts == expected
# Tests for the new TTS markup format parsing
@pytest.mark.parametrize(
"input, expected",
[
# Empty input
("", []),
# Simple narrator line
(
"[Narrator] He walked into the room.",
[
{
"text": "He walked into the room.",
"type": "exposition",
"speaker": None,
}
],
),
# Simple dialogue line
(
"[John] Hello world.",
[{"text": "Hello world.", "type": "dialogue", "speaker": "John"}],
),
# Mixed dialogue and narration
(
"[Narrator] He said\n[John] Hello world\n[Narrator] and walked away.",
[
{"text": "He said", "type": "exposition", "speaker": None},
{"text": "Hello world", "type": "dialogue", "speaker": "John"},
{"text": "and walked away.", "type": "exposition", "speaker": None},
],
),
# Multiple speakers
(
"[John] Hi there\n[Mary] Hello back\n[John] How are you?",
[
{"text": "Hi there", "type": "dialogue", "speaker": "John"},
{"text": "Hello back", "type": "dialogue", "speaker": "Mary"},
{"text": "How are you?", "type": "dialogue", "speaker": "John"},
],
),
# Line without proper format (fallback to exposition)
(
"Some random text without brackets",
[
{
"text": "Some random text without brackets",
"type": "exposition",
"speaker": None,
}
],
),
# Empty lines should be ignored
(
"[John] Hello\n\n[Mary] Hi\n",
[
{"text": "Hello", "type": "dialogue", "speaker": "John"},
{"text": "Hi", "type": "dialogue", "speaker": "Mary"},
],
),
# Different narrator casings
(
"[NARRATOR] Some narration\n[narrator] More narration",
[
{"text": "Some narration", "type": "exposition", "speaker": None},
{"text": "More narration", "type": "exposition", "speaker": None},
],
),
],
)
def test_parse_tts_markup(input, expected):
"""Test the parse_tts_markup function that handles the new [Speaker] format."""
from talemate.util.dialogue import parse_tts_markup
result = parse_tts_markup(input)
# Convert result to list of dicts for easier comparison
result_dicts = [
{"text": chunk.text, "type": chunk.type, "speaker": chunk.speaker}
for chunk in result
]
assert result_dicts == expected