awacke1 commited on
Commit
39fa99f
Β·
verified Β·
1 Parent(s): b70c878

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -144
app.py CHANGED
@@ -1,148 +1,71 @@
1
  import streamlit as st
2
- from streamlit.components.v1 import html
3
-
4
-
5
- state = st.session_state
6
- if 'my_value' not in state:
7
- state['my_value'] = None
8
- if st.button('Set value'):
9
- state['my_value'] = 'some_value'
10
- if state['my_value'] is not None:
11
- st.write(f'<a href="?my_param={state["my_value"]}">Click here to see the value in the URL</a>')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- if state['my_value'] is not None:
14
- st.markdown(state['my_value'])
15
 
16
- if state['my_value'] is not None:
17
- st.write(f'<a href="?my_param={state["my_value"]}">Click here to see the value in the URL</a>')
18
-
19
-
20
-
21
 
22
- #from streamlit_cookies_controller import CookieController
23
-
24
- #st.set_page_config('Cookie QuickStart', 'πŸͺ', layout='wide')
25
-
26
- #controller = CookieController()
27
-
28
- # Set a cookie
29
- #controller.set('cookie_name', 'testing')
30
-
31
- # Get all cookies
32
- #cookies = controller.getAll()
33
-
34
- # Get a cookie
35
- #cookie = controller.get('cookie_name')
36
-
37
- # Remove a cookie
38
- #controller.remove('cookie_name')
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
- # Debugging Headers and Cookies
47
- # st.write("Headers:", st.context.headers)
48
- st.write("Cookies:", st.context.cookies)
49
-
50
- # Define JavaScript code
51
- javascript_code = """
52
- <script>
53
- // Function to return a string
54
- function myJavaScriptFunction() {
55
- return "Hello from JavaScript!";
56
- }
57
-
58
- // Function to call and send data back to Python
59
- function callAndCapture() {
60
- const result = myJavaScriptFunction();
61
- // Send the result back to Streamlit
62
- window.parent.postMessage({ isStreamlitMessage: true, type: 'streamlit:js_return', data: result }, '*');
63
- }
64
-
65
- // Add an event listener to listen for messages from Streamlit
66
- window.addEventListener('message', function(event) {
67
- if (event.data && event.data.type === 'streamlit:buttonClick') {
68
- callAndCapture();
69
- }
70
- });
71
- </script>
72
- <button onclick="callAndCapture()">Run JavaScript Function</button>
73
- """
74
-
75
- # Embed JavaScript into Streamlit app
76
- html(javascript_code, height=300)
77
-
78
- # Placeholder to display results
79
- result_placeholder = st.empty()
80
-
81
- # Add Streamlit button to trigger JavaScript function
82
- if st.button("Call JavaScript Function"):
83
- st.write("Waiting for JavaScript response...")
84
- trigger_js = """
85
- <script>
86
- // Trigger the JavaScript function via a postMessage event
87
- window.parent.postMessage({ type: 'streamlit:buttonClick' }, '*');
88
- </script>
89
- """
90
- html(trigger_js, height=0)
91
-
92
- # Add a listener for JavaScript responses
93
- st.markdown(
94
- """
95
- <script>
96
- // Listen for messages from JavaScript
97
- window.addEventListener('message', (event) => {
98
- if (event.data && event.data.type === 'streamlit:js_return') {
99
- // Pass the data back to Streamlit as a new message
100
- const result = event.data.data;
101
- document.dispatchEvent(new CustomEvent('StreamlitResult', { detail: result }));
102
- }
103
- });
104
-
105
- // Dispatch data from CustomEvent to Streamlit
106
- document.addEventListener('StreamlitResult', (e) => {
107
- const data = e.detail;
108
- window.parent.postMessage({ type: 'streamlit:result', data: data }, '*');
109
- });
110
- </script>
111
- """,
112
- unsafe_allow_html=True,
113
- )
114
-
115
- # Use an iframe for communication
116
- if "js_result" not in st.session_state:
117
- st.session_state["js_result"] = ""
118
-
119
- try:
120
- # Listen for result data from JavaScript
121
- received_result = html(
122
- """
123
- <script>
124
- window.addEventListener('message', (event) => {
125
- if (event.data && event.data.type === 'streamlit:result') {
126
- const data = event.data.data;
127
- // Send the result back to Streamlit
128
- document.dispatchEvent(new CustomEvent('PythonReceivedResult', { detail: data }));
129
- }
130
- });
131
-
132
- document.addEventListener('PythonReceivedResult', (e) => {
133
- const received = e.detail;
134
- document.getElementById('result-placeholder').innerText = received;
135
- });
136
- </script>
137
- <div id="result-placeholder"></div>
138
- """,
139
- height=0,
140
- )
141
-
142
- # If there's a new result, update it in session state
143
- if received_result and received_result != st.session_state["js_result"]:
144
- st.session_state["js_result"] = received_result
145
- result_placeholder.write(f"Result from JavaScript: {received_result}")
146
-
147
- except Exception as e:
148
- st.error(f"An error occurred: {e}")
 
1
  import streamlit as st
2
+ from pathlib import Path
3
+ import json
4
+
5
+ # πŸ¦„ Magical state initialization
6
+ if 'file_data' not in st.session_state:
7
+ st.session_state.file_data = {}
8
+
9
+ def save_to_file(data, filename):
10
+ """🌈 Rainbow file saver - spreading joy through data persistence!"""
11
+ try:
12
+ with open(filename, 'w') as f:
13
+ json.dump(data, f)
14
+ return True
15
+ except Exception as e:
16
+ st.error(f"Oopsie! πŸ™ˆ Couldn't save to {filename}: {str(e)}")
17
+ return False
18
+
19
+ def load_from_file(filename):
20
+ """πŸŽ€ Pretty file loader - bringing your data back with style!"""
21
+ try:
22
+ with open(filename, 'r') as f:
23
+ return json.load(f)
24
+ except FileNotFoundError:
25
+ st.info(f"✨ New adventure! No previous data found in {filename}")
26
+ return {}
27
+ except json.JSONDecodeError:
28
+ st.warning(f"🎭 Hmm, the file {filename} contains invalid JSON. Starting fresh!")
29
+ return {}
30
+
31
+ def main():
32
+ st.title("πŸŽ‰ Super Fun File Handler!")
33
 
34
+ # 🎨 Pretty file upload section
35
+ uploaded_file = st.file_uploader("Upload your happy little file!", type=['txt', 'json'])
36
 
37
+ if uploaded_file:
38
+ # πŸŽͺ Process the uploaded file with circus-level excitement!
39
+ content = uploaded_file.getvalue().decode()
40
+ st.session_state.file_data[uploaded_file.name] = content
41
+ st.success(f"🌟 Woohoo! Successfully loaded {uploaded_file.name}")
42
 
43
+ # 🎠 Display our magical collection of files
44
+ if st.session_state.file_data:
45
+ st.subheader("πŸ—‚οΈ Your Wonderful Files:")
46
+ for filename, content in st.session_state.file_data.items():
47
+ with st.expander(f"πŸ“ {filename}"):
48
+ st.text_area("Content", content, height=150, key=filename)
49
+
50
+ if st.button(f"πŸ’Ύ Save changes to {filename}"):
51
+ updated_content = st.session_state[filename]
52
+ if save_to_file(updated_content, filename):
53
+ st.success(f"πŸŽ‰ Yay! Saved {filename} successfully!")
54
+
55
+ # πŸŽͺ System prompt section
56
+ st.subheader("πŸ€– Super Smart System Prompt Generator")
57
+ if st.session_state.file_data:
58
+ selected_files = st.multiselect(
59
+ "Select files for your prompt",
60
+ list(st.session_state.file_data.keys())
61
+ )
62
+
63
+ if selected_files:
64
+ prompt = "Here are the contents of the selected files:\n\n"
65
+ for file in selected_files:
66
+ prompt += f"File: {file}\n```\n{st.session_state.file_data[file]}\n```\n\n"
67
+
68
+ st.text_area("Generated Prompt", prompt, height=300)
69
+
70
+ if __name__ == "__main__":
71
+ main()