Last active
March 18, 2024 11:05
-
-
Save andfanilo/a4f8a56d30da9e9d9122ea0d6ecb6894 to your computer and use it in GitHub Desktop.
Streamlit IPython History Browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from datetime import datetime | |
import streamlit as st | |
from IPython.core.history import HistoryAccessor | |
@dataclass | |
class IPythonSession: | |
session_id: int | |
start: datetime | |
end: datetime | |
num_cmds: int | |
remark: str | |
def get_history(profile_name): | |
return HistoryAccessor(profile=profile_name) | |
def load_all_sessions(profile_history): | |
last_session_id = profile_history.get_last_session_id() | |
all_sessions = [ | |
IPythonSession(*profile_history.get_session_info(i)) | |
for i in range(last_session_id) | |
if profile_history.get_session_info(i) is not None | |
] | |
all_sessions_with_code = [ | |
sess for sess in all_sessions if sess.num_cmds is not None and sess.num_cmds > 0 | |
] | |
return all_sessions_with_code | |
def main(): | |
profile_history = get_history("default") | |
selected_page = st.sidebar.selectbox("Select page", ("browser", "search")) | |
if selected_page == "browser": | |
browser(profile_history) | |
if selected_page == "search": | |
searcher(profile_history) | |
def browser(profile_history: HistoryAccessor): | |
all_sessions = load_all_sessions(profile_history) | |
session_id_to_start = { | |
s.session_id: f"Session {s.session_id} -{s.start.ctime()}" for s in all_sessions | |
} | |
with st.sidebar: | |
selected_session = st.selectbox( | |
"Select IPython Session", | |
list(session_id_to_start.keys())[::-1], | |
format_func=lambda i: session_id_to_start[i], | |
) | |
code_history = [c[2] for c in profile_history.get_range(selected_session)] | |
st.code("\n".join(code_history)) | |
def searcher(profile_history: HistoryAccessor): | |
code_to_search = st.sidebar.text_input("Enter code to search") | |
n_entries = st.sidebar.number_input("Maximum number of entries", 3, 500, 20) | |
if code_to_search == "": | |
return | |
code_history = [ | |
f"**{c[0]}:{c[1]}** | `{c[2]}`" | |
for c in profile_history.search(code_to_search, n=n_entries) | |
] | |
st.markdown("\n\n".join(code_history)) | |
if __name__ == "__main__": | |
st.set_page_config(page_title="IPython History Browser", page_icon="book") | |
st.title("IPython History Accessor") | |
st.sidebar.header("Configuration") | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output