|
| 1 | +import streamlit as st |
| 2 | +from ghostos.helpers import yaml_pretty_dump |
| 3 | +from ghostos.prototypes.streamlitapp.pages.router import ShowThreadRoute |
| 4 | +from ghostos.prototypes.streamlitapp.resources import get_container, get_app_conf |
| 5 | +from ghostos.prototypes.streamlitapp.widgets.renderer import render_thread |
| 6 | +from ghostos.core.runtime.threads import GoThreads, GoThreadInfo, thread_to_markdown |
| 7 | +import os |
| 8 | +import yaml |
| 9 | + |
| 10 | + |
| 11 | +def show_thread(): |
| 12 | + st.title("Show Thread Info") |
| 13 | + route = ShowThreadRoute().get_or_bind(st.session_state) |
| 14 | + |
| 15 | + thread_id = route.thread_id |
| 16 | + if not thread_id: |
| 17 | + st.error("No thread specified") |
| 18 | + return |
| 19 | + container = get_container() |
| 20 | + threads = container.force_fetch(GoThreads) |
| 21 | + |
| 22 | + thread = threads.get_thread(thread_id, create=False) |
| 23 | + if not thread: |
| 24 | + filename = os.path.abspath(thread_id) |
| 25 | + if os.path.exists(filename): |
| 26 | + with open(filename, "rb") as f: |
| 27 | + content = f.read() |
| 28 | + data = yaml.safe_load(content) |
| 29 | + thread = GoThreadInfo(**data) |
| 30 | + |
| 31 | + if not thread: |
| 32 | + st.error(f"Thread {thread_id} does not exist") |
| 33 | + return |
| 34 | + |
| 35 | + with st.sidebar: |
| 36 | + if filename := st.text_input("output markdown filename (without `.md`)"): |
| 37 | + try: |
| 38 | + saved_at = save_thread_markdown_file(thread, filename) |
| 39 | + st.info(f"save thread as markdown file: {saved_at}") |
| 40 | + except Exception as e: |
| 41 | + st.error(e) |
| 42 | + |
| 43 | + desc = thread.model_dump(include={"id", "parent_id", "root_id", "extra"}) |
| 44 | + st.markdown(f""" |
| 45 | +```yaml |
| 46 | +{yaml_pretty_dump(desc)} |
| 47 | +``` |
| 48 | +""") |
| 49 | + is_debug = get_app_conf().BoolOpts.DEBUG_MODE.get() |
| 50 | + render_thread(thread, debug=is_debug) |
| 51 | + |
| 52 | + |
| 53 | +def save_thread_markdown_file(thread: GoThreadInfo, filename: str) -> str: |
| 54 | + if not filename.endswith(".md"): |
| 55 | + filename = filename + ".md" |
| 56 | + |
| 57 | + filename = os.path.abspath(filename) |
| 58 | + content = thread_to_markdown(thread) |
| 59 | + with open(filename, "w") as f: |
| 60 | + f.write(content) |
| 61 | + open_dialog_markdown_content(content) |
| 62 | + return filename |
| 63 | + |
| 64 | + |
| 65 | +@st.dialog("Thread Markdown Output", width="large") |
| 66 | +def open_dialog_markdown_content(content: str): |
| 67 | + st.markdown(content, unsafe_allow_html=False) |
0 commit comments