Spaces:
Sleeping
Sleeping
File size: 17,361 Bytes
cf07abe cdb2e44 cf07abe 26b53ab 6d154df |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 |
---
title: CatRider
emoji: π±ποΈπ
colorFrom: indigo
colorTo: green
sdk: streamlit
sdk_version: 1.38.0
app_file: app.py
pinned: false
license: mit
---
Explanation of Updates:
Renamed the Graph Function and Title:
Renamed the function create_heterogeneous_graph to create_knowledge_graph to match your request.
Changed the display title from "Your Journey (Heterogeneous Graph)" to "Your Journey (Knowledge Graph)".
Adjusted the function calls in the main application to reflect the new function name.
Modified the Graph Structure in create_knowledge_graph:
Situation Nodes:
Each unique situation is represented by a single node.
Created a node for each situation only once by checking if the situation node ID is already in node_ids.
Attempt Nodes:
For each action (attempt), created a child node under the corresponding situation node.
The attempt node includes the action, outcome, conclusion, and stars reflecting the score.
Edges:
Created an edge from the situation node to each attempt node.
This results in a tree structure under each situation node showing all attempts.
python
Copy code
def create_knowledge_graph(history_df):
nodes = []
edges = []
node_ids = {}
for index, row in history_df.iterrows():
situation_node_id = f"situation_{row['situation_id']}"
action_node_id = f"action_{index}"
# Situation node
if situation_node_id not in node_ids:
situation_node = StreamlitFlowNode(
situation_node_id,
pos=(0, 0),
data={'content': f"{row['situation_emoji']} {row['situation_name']}"},
type='default',
shape='ellipse'
)
nodes.append(situation_node)
node_ids[situation_node_id] = situation_node_id
# Attempt node (action and outcome)
outcome_content = 'β
Success' if row['outcome'] else 'β Failure'
stars = 'β' * int(row['score'])
attempt_node = StreamlitFlowNode(
action_node_id,
pos=(0, 0),
data={'content': f"{row['action_emoji']} {row['action_name']} ({outcome_content})\n{row['conclusion']}\n{stars}"},
type='default',
shape='rectangle'
)
nodes.append(attempt_node)
# Edge from situation to attempt
edges.append(StreamlitFlowEdge(
id=f"edge_{situation_node_id}_{action_node_id}",
source=situation_node_id,
target=action_node_id,
animated=True
))
return nodes, edges
Updated the Markdown Preview in create_markdown_preview:
Modified the markdown structure to group attempts under each unique situation, regardless of the attempt number.
The output now matches the format you provided, showing multiple attempts per situation.
python
Copy code
def create_markdown_preview(history_df):
markdown = "## π³ Journey Preview\n\n"
grouped = history_df.groupby(['situation_name'], sort=False)
for situation_name, group in grouped:
markdown += f"### {group.iloc[0]['situation_emoji']} **{situation_name}**\n"
for _, row in group.iterrows():
outcome_str = 'β
Success' if row['outcome'] else 'β Failure'
stars = 'β' * int(row['score'])
markdown += f"- Attempt {row['attempt']}: {row['action_emoji']} **{row['action_name']}**: {outcome_str} {stars}\n"
markdown += f" - {row['conclusion']}\n"
markdown += "\n"
return markdown
Ensured the Graph Reflects the Journey Preview:
The graph now displays each unique situation once, with all attempts as child nodes.
This results in multiple trees, one for each situation, matching the three trees in your example.
Adjusted the Main Function to Reflect Changes:
Updated the function calls to use create_knowledge_graph instead of create_heterogeneous_graph.
Changed the display title accordingly.
python
Copy code
# Integration point for both functions
if not game_state['history_df'].empty:
# π Display Markdown Preview
st.markdown(create_markdown_preview(game_state['history_df']))
# π³ Display Knowledge Journey Graph
st.markdown("## π³ Your Journey (Knowledge Graph)")
nodes, edges = create_knowledge_graph(game_state['history_df'])
try:
streamlit_flow('cat_rider_flow',
nodes,
edges,
layout=TreeLayout(direction='down'),
fit_view=True,
height=600)
except Exception as e:
st.error(f"An error occurred while rendering the journey graph: {str(e)}")
st.markdown("Please try refreshing the page if the graph doesn't appear.")
How It Now Works:
Graph Structure:
Each unique situation is a node in the graph.
All attempts (actions taken) under a situation are child nodes connected to the situation node.
Both failures and successes are displayed as child nodes.
This creates a tree structure for each situation, reflecting the multiple attempts.
Journey Preview:
The markdown preview shows the situations, with attempts listed under each.
Attempts include the action taken, outcome, score (stars), and conclusion.
The format matches the example you provided.
Multiple Trees:
If the player encounters multiple unique situations, the graph will display multiple trees.
Each tree represents a situation with its attempts.
This provides a clear visual of the player's journey through different scenarios.
Example Output:
Assuming the player has the following history:
The Great Feline Escape:
Attempt 1: Negotiate β Failure
Attempt 2: Sprint Away β Success
The Royal Tournament:
Attempt 1: Sprint Away β Success
Attempt 2: Show Bravery β Failure
Attempt 3: Negotiate β Success
The Great Cheese Heist:
Attempt 1: Develop a Strategy β Success
The graph will have three situation nodes:
The Great Feline Escape
Child Nodes:
Negotiate (Failure)
Sprint Away (Success)
The Royal Tournament
Child Nodes:
Sprint Away (Success)
Show Bravery (Failure)
Negotiate (Success)
The Great Cheese Heist
Child Nodes:
Develop a Strategy (Success)
Running the Updated Code:
Ensure Required Libraries Are Installed:
bash
Copy code
pip install streamlit pandas plotly streamlit-flow
Save the Code:
Save the updated code into a file, e.g., cat_rider_game.py.
Run the Streamlit App:
bash
Copy code
streamlit run cat_rider_game.py
Play the Game:
Choose your Cat Rider and Riding Gear.
Engage in adventures and make decisions.
View the updated Journey Preview and Knowledge Graph after each action.
Save and download your game histories via the sidebar.
Note:
If you encounter any issues with the streamlit-flow library, ensure it is correctly installed and compatible with your environment.
The code assumes that the StreamlitFlowNode and StreamlitFlowEdge classes accept the parameters as specified. If not, you may need to adjust the parameter names according to the library's documentation.
Conclusion:
This updated code reflects your requirements by:
Changing the graph to "Knowledge Graph".
Displaying each situation once in the graph, with attempts as child nodes.
Matching the Journey Preview format you provided.
Providing a clear visualization of the player's journey with multiple trees for unique situations.
---
Example of AIPP:
Journey Preview aggregates the history correctly. Your Journey does not. I want the creation of the knowledge graph to be much more detail with every action and outcome shown in the graph. Currently it will only show the first one. Use this as a test case which should create 5 different nodes each showing the full story and then use connectors to join them all to eachother as a mind map. π³ Journey Preview
π€ ('The Eternal Catnap',)
Attempt 2: π Showcase Agility: β Failure You tripped over your own paws! πΎ Attempt 3: π Showcase Agility: β Failure The enemy was too clever for your plan. π§ Attempt 3: πͺ Create a Distraction: β
Success β Victory is sweet, just like a bowl of fresh milk! π₯ For the demo - I want a graph very similar to Markdown Node demo below: import streamlit as st
from streamlit_flow import streamlit_flow
from streamlit_flow.elements import StreamlitFlowNode, StreamlitFlowEdge
from streamlit_flow.layouts import RadialLayout
st.set_page_config(page_title="Markdown Node - Streamlit Flow", layout="wide")
st.title("Markdown Node Demo")
st.markdown("""The `StreamlitFlowNode` takes as input `content` within its `data` attribute which can either be plaintext, markdown or HTML.
This can be made to show a variety of content within the node. Below is an example of a node with markdown content.""")
nodes = [StreamlitFlowNode("main", (0, 0), {'content':"# Markdown Support in Nodes"}, 'input', 'bottom', width=400),
StreamlitFlowNode("text", (0, 0), {'content':
"""### Text
Can support markdown text styles: **bold**, *italic* and `code`"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("code", (0, 0), {'content':
"""### Code Block
```python
print('Hello World')
```"""},'output', 'bottom', 'top'),
StreamlitFlowNode("list", (0, 0), {'content':
"""### List
1. Ordered
2. And
- Unordered
- Lists
"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("math", (0, 0), {'content':
"""### Math
$\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$
"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("github", (0, 0), {'content': '## Github Flavor Support'}, 'default', 'top', 'bottom'),
StreamlitFlowNode("strikethrough", (0, 0), {'content':
"""
### ~Strike through~
"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("table", (0, 0), {'content':
"""### Table
| a | b | c | d |
| - | :- | -: | :-: |
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
"""}, 'output', 'top', 'right', width=160),
StreamlitFlowNode("tasks", (0, 0), {'content':
"""## Tasklist
* [ ] to do
* [x] done
"""}, 'output', 'top', 'bottom'),
StreamlitFlowNode("html", (0, 0), {'content':
"""## Raw HTML"""}, 'default', 'top', 'bottom', width=200),
StreamlitFlowNode("link", (0, 0), {'content':
"""### Link
<a href="https://github.com/dkapur17/streamlit-flow" target="_blank">Streamlit Flow</a>"""}, 'output', 'top', 'bottom'),
StreamlitFlowNode("expander", (0, 0), {'content':
"""### Expander
<details>
<summary>Click to expand</summary>
This is hidden content
</details>
"""}, 'output', 'top', 'bottom'),
StreamlitFlowNode("image",(0, 0), {'content':
"""### Image
<img src="https://raw.githubusercontent.com/dkapur17/streamlit-flow/master/assets/streamlit-flow-logo.svg" alt="Streamlit Flow Logo" width="100">
"""}, 'output', 'top', 'bottom', width=120),
StreamlitFlowNode("video", (0, 0), {'content':
"""### Video
<video width="256" controls>
<source src="https://github.com/dkapur17/streamlit-flow/raw/master/assets/FastBuild.mp4" type="video/mp4">
</video>
"""}, 'output', 'bottom', 'top', width=300)]
edges = [StreamlitFlowEdge("main-text", "main", "text", animated=True),
StreamlitFlowEdge("main-code", "main", "code", animated=True),
StreamlitFlowEdge("main-list", "main", "list", animated=True),
StreamlitFlowEdge("main-math", "main", "math", animated=True),
StreamlitFlowEdge("main-github", "main", "github", animated=True),
StreamlitFlowEdge("github-strikethrough", "github", "strikethrough", animated=True),
StreamlitFlowEdge("github-table", "github", "table", animated=True),
StreamlitFlowEdge("github-tasks", "github", "tasks", animated=True),
StreamlitFlowEdge("main-html", "main", "html", animated=True),
StreamlitFlowEdge("html-link", "html", "link", animated=True),
StreamlitFlowEdge("html-expander", "html", "expander", animated=True),
StreamlitFlowEdge("html-image", "html", "image", animated=True),
StreamlitFlowEdge("html-video", "html", "video", animated=True)]
streamlit_flow('markdown_node_flow', nodes, edges, layout=RadialLayout(), fit_view=True, height=1000)
st.divider()
with st.expander("Spolier"):
st.code("""
from streamlit_flow import streamlit_flow
from streamlit_flow.elements import StreamlitFlowNode, StreamlitFlowEdge
from streamlit_flow.layouts import RadialLayout
nodes = [StreamlitFlowNode("main", (0, 0), {'content':"# Markdown Support in Nodes"}, 'input', 'bottom', width=400),
StreamlitFlowNode("text", (0, 0), {'content':
\"""### Text
Can support markdown text styles: **bold**, *italic* and `code`\"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("code", (0, 0), {'content':
\"""### Code Block
```python
print('Hello World')
```\"""},'output', 'bottom', 'top'),
StreamlitFlowNode("list", (0, 0), {'content':
\"""### List
1. Ordered
2. And
- Unordered
- Lists
\"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("math", (0, 0), {'content':
\"""### Math
$\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}$
\"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("github", (0, 0), {'content': '## Github Flavor Support'}, 'default', 'top', 'bottom'),
StreamlitFlowNode("strikethrough", (0, 0), {'content':
\"""
### ~Strike through~
\"""}, 'output', 'bottom', 'top'),
StreamlitFlowNode("table", (0, 0), {'content':
\"""### Table
| a | b | c | d |
| - | :- | -: | :-: |
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
\"""}, 'output', 'top', 'right', width=160),
StreamlitFlowNode("tasks", (0, 0), {'content':
\"""## Tasklist
* [ ] to do
* [x] done
\"""}, 'output', 'top', 'bottom'),
StreamlitFlowNode("html", (0, 0), {'content':
\"""## Raw HTML\"""}, 'default', 'top', 'bottom', width=200),
StreamlitFlowNode("link", (0, 0), {'content':
\"""### Link
<a href="https://github.com/dkapur17/streamlit-flow" target="_blank">Streamlit Flow</a>\"""}, 'output', 'top', 'bottom'),
StreamlitFlowNode("expander", (0, 0), {'content':
\"""### Expander
<details>
<summary>Click to expand</summary>
This is hidden content
</details>
\"""}, 'output', 'top', 'bottom'),
StreamlitFlowNode("image",(0, 0), {'content':
\"""### Image
<img src="https://raw.githubusercontent.com/dkapur17/streamlit-flow/master/assets/streamlit-flow-logo.svg" alt="Streamlit Flow Logo" width="100">
\"""}, 'output', 'top', 'bottom', width=120),
StreamlitFlowNode("video", (0, 0), {'content':
\"""### Video
<video width="256" controls>
<source src="https://github.com/dkapur17/streamlit-flow/raw/master/assets/FastBuild.mp4" type="video/mp4">
</video>
\"""}, 'output', 'bottom', 'top', width=300)]
edges = [StreamlitFlowEdge("main-text", "main", "text", animated=True),
StreamlitFlowEdge("main-code", "main", "code", animated=True),
StreamlitFlowEdge("main-list", "main", "list", animated=True),
StreamlitFlowEdge("main-math", "main", "math", animated=True),
StreamlitFlowEdge("main-github", "main", "github", animated=True),
StreamlitFlowEdge("github-strikethrough", "github", "strikethrough", animated=True),
StreamlitFlowEdge("github-table", "github", "table", animated=True),
StreamlitFlowEdge("github-tasks", "github", "tasks", animated=True),
StreamlitFlowEdge("main-html", "main", "html", animated=True),
StreamlitFlowEdge("html-link", "html", "link", animated=True),
StreamlitFlowEdge("html-expander", "html", "expander", animated=True),
StreamlitFlowEdge("html-image", "html", "image", animated=True),
StreamlitFlowEdge("html-video", "html", "video", animated=True)]
streamlit_flow('example_flow',
nodes,
edges,
layout=RadialLayout(),
fit_view=True,
height=1000)
""") Also add this atop of the code so I can always be in wide mode. # 1. Configuration
Site_Name = 'π¦CatRiderπ'
title="π¦CatRiderπbyπ€Aaron Wacker"
helpURL='https://huggingface.co/awacke1'
bugURL='https://huggingface.co/spaces/awacke1'
icons='π¦'
useConfig=True
if useConfig: # Component code - useConfig=False should allow it to work if re-evaluating UI elements due to code modify
st.set_page_config(
page_title=title,
page_icon=icons,
layout="wide",
#initial_sidebar_state="expanded",
initial_sidebar_state="auto",
menu_items={
'Get Help': helpURL,
'Report a bug': bugURL,
'About': title
}
)
π ('The Royal Tournament',)
Attempt 2: πββοΈ Sprint Away: β Failure The cat gods were not in your favor today. π Attempt 2: π¦ Show Bravery: β
Success ββ Youβve earned the title of Cat Commander! π
Attempt 2: π§ Be Resourceful: β Failure The challenge was too great this time. Better luck next time! π
π½ ('The Feline Invasion',)
Attempt 1: π Showcase Agility: β
Success βββ Youβve earned the title of Cat Commander! π
π ('The Feline Moon Mission',)
Attempt 1: π§ Be Resourceful: β
Success ββββ Your strategy was flawless, and the victory is yours! ποΈ
πͺ ('The Great Feline Escape',)
Attempt 1: π§ Be Resourceful: β
Success βββββ All the other cats are jealous of your agility! πββοΈ
π³ Your Journey (Knowledge Graph) |