awacke1 commited on
Commit
b5ee896
Β·
verified Β·
1 Parent(s): cdca39a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +238 -0
app.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit.components.v1 import html
3
+ from pathlib import Path
4
+ import json
5
+ import time
6
+ from datetime import datetime
7
+ import re
8
+ import pandas as pd
9
+ import yaml
10
+ from io import StringIO
11
+ import openpyxl
12
+ import csv
13
+ import base64
14
+
15
+ # Supported file types and their handlers
16
+ FILE_TYPES = {
17
+ "md": "πŸ“ Markdown",
18
+ "txt": "πŸ“„ Text",
19
+ "json": "πŸ”§ JSON",
20
+ "csv": "πŸ“Š CSV",
21
+ "xlsx": "πŸ“— Excel",
22
+ "yaml": "βš™οΈ YAML",
23
+ "xml": "πŸ”— XML"
24
+ }
25
+
26
+ # Enhanced state initialization
27
+ if 'file_data' not in st.session_state:
28
+ st.session_state.file_data = {}
29
+ if 'file_types' not in st.session_state:
30
+ st.session_state.file_types = {}
31
+ if 'md_outline' not in st.session_state:
32
+ st.session_state.md_outline = {}
33
+ if 'rendered_content' not in st.session_state:
34
+ st.session_state.rendered_content = {}
35
+ if 'file_history' not in st.session_state:
36
+ st.session_state.file_history = []
37
+ if 'md_versions' not in st.session_state:
38
+ st.session_state.md_versions = {}
39
+ if 'md_files_history' not in st.session_state:
40
+ st.session_state.md_files_history = []
41
+ if 'combined_markdown' not in st.session_state:
42
+ st.session_state.combined_markdown = ""
43
+
44
+ def delete_all_md_files():
45
+ """Delete all markdown files except README.md"""
46
+ files_to_remove = [
47
+ f for f in st.session_state.md_files_history
48
+ if f["filename"] != "README.md"
49
+ ]
50
+ for file in files_to_remove:
51
+ filename = file["filename"]
52
+ if filename in st.session_state.file_data:
53
+ del st.session_state.file_data[filename]
54
+ if filename in st.session_state.file_types:
55
+ del st.session_state.file_types[filename]
56
+ if filename in st.session_state.md_outline:
57
+ del st.session_state.md_outline[filename]
58
+ if filename in st.session_state.rendered_content:
59
+ del st.session_state.rendered_content[filename]
60
+ if filename in st.session_state.md_versions:
61
+ del st.session_state.md_versions[filename]
62
+
63
+ st.session_state.md_files_history = [
64
+ f for f in st.session_state.md_files_history
65
+ if f["filename"] == "README.md"
66
+ ]
67
+ st.session_state.combined_markdown = ""
68
+ return len(files_to_remove)
69
+
70
+ def get_binary_file_downloader_html(bin_file, file_label='File'):
71
+ """Generate a link allowing the data in a given file to be downloaded"""
72
+ b64 = base64.b64encode(bin_file.encode()).decode()
73
+ return f'<a href="data:text/plain;base64,{b64}" download="{file_label}">πŸ“₯ Download {file_label}</a>'
74
+
75
+ def encode_content(content):
76
+ """Encode content to base64"""
77
+ return base64.b64encode(content.encode()).decode()
78
+
79
+ def decode_content(encoded_content):
80
+ """Decode content from base64"""
81
+ return base64.b64decode(encoded_content.encode()).decode()
82
+
83
+ def combine_markdown_files():
84
+ """Combine all markdown files into a single document"""
85
+ combined = []
86
+ for md_file in sorted(st.session_state.md_files_history, key=lambda x: x["filename"]):
87
+ content = decode_content(md_file["content"])
88
+ combined.append(f"# {md_file['filename']}\n\n{content}\n\n---\n\n")
89
+ return "".join(combined)
90
+
91
+ def add_to_history(filename, content, action="uploaded"):
92
+ """Add a file action to the history with timestamp"""
93
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
94
+ encoded_content = encode_content(content)
95
+ history_entry = {
96
+ "timestamp": timestamp,
97
+ "filename": filename,
98
+ "action": action,
99
+ "content": encoded_content
100
+ }
101
+ st.session_state.file_history.insert(0, history_entry)
102
+
103
+ # Store version if it's a markdown file
104
+ if filename.endswith('.md'):
105
+ if filename not in st.session_state.md_versions:
106
+ st.session_state.md_versions[filename] = []
107
+ st.session_state.md_versions[filename].append({
108
+ "timestamp": timestamp,
109
+ "content": encoded_content,
110
+ "action": action
111
+ })
112
+
113
+ # Add to MD files history if not already present
114
+ if filename not in [f["filename"] for f in st.session_state.md_files_history]:
115
+ st.session_state.md_files_history.append({
116
+ "filename": filename,
117
+ "timestamp": timestamp,
118
+ "content": encoded_content
119
+ })
120
+
121
+ # Update combined markdown
122
+ st.session_state.combined_markdown = combine_markdown_files()
123
+
124
+ def show_sidebar_history():
125
+ """Display markdown file history in the sidebar"""
126
+ st.sidebar.markdown("### πŸ“š Markdown Files History")
127
+
128
+ # Add Delete All button
129
+ if st.sidebar.button("πŸ—‘οΈ Delete All (except README.md)"):
130
+ deleted_count = delete_all_md_files()
131
+ st.sidebar.success(f"Deleted {deleted_count} markdown files")
132
+ st.experimental_rerun()
133
+
134
+ for md_file in st.session_state.md_files_history:
135
+ col1, col2, col3 = st.sidebar.columns([2, 1, 1])
136
+
137
+ with col1:
138
+ st.markdown(f"**{md_file['filename']}**")
139
+
140
+ with col2:
141
+ if st.button("πŸ“‚ Open", key=f"open_{md_file['filename']}"):
142
+ content = decode_content(md_file['content'])
143
+ st.session_state.file_data[md_file['filename']] = content
144
+ st.session_state.file_types[md_file['filename']] = "md"
145
+ st.session_state.md_outline[md_file['filename']] = parse_markdown_outline(content)
146
+ st.experimental_rerun()
147
+
148
+ with col3:
149
+ download_link = get_binary_file_downloader_html(
150
+ decode_content(md_file['content']),
151
+ md_file['filename']
152
+ )
153
+ st.markdown(download_link, unsafe_allow_html=True)
154
+
155
+ def show_book_view():
156
+ """Display all markdown files in a book-like format"""
157
+ if st.session_state.combined_markdown:
158
+ st.markdown("## πŸ“– Book View")
159
+ st.markdown(st.session_state.combined_markdown)
160
+
161
+ # [Previous functions remain the same: show_file_history, show_markdown_versions,
162
+ # parse_markdown_outline, create_markdown_tabs, read_file_content, save_file_content]
163
+
164
+ def main():
165
+ st.title("πŸ“šβœ¨ Super Smart File Handler with Markdown Magic! βœ¨πŸ“š")
166
+
167
+ # Show markdown history in sidebar
168
+ show_sidebar_history()
169
+
170
+ # Add tabs for different upload methods
171
+ upload_tab, book_tab = st.tabs(["πŸ“€ File Upload", "πŸ“– Book View"])
172
+
173
+ with upload_tab:
174
+ col1, col2 = st.columns(2)
175
+
176
+ with col1:
177
+ uploaded_file = st.file_uploader(
178
+ "πŸ“€ Upload single file",
179
+ type=list(FILE_TYPES.keys()),
180
+ help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()])
181
+ )
182
+
183
+ with col2:
184
+ uploaded_files = st.file_uploader(
185
+ "πŸ“š Upload multiple files",
186
+ type=list(FILE_TYPES.keys()),
187
+ accept_multiple_files=True,
188
+ help="Upload multiple files to view as a book"
189
+ )
190
+
191
+ # Process single file upload
192
+ if uploaded_file:
193
+ content, file_type = read_file_content(uploaded_file)
194
+ if content is not None:
195
+ st.session_state.file_data[uploaded_file.name] = content
196
+ st.session_state.file_types[uploaded_file.name] = file_type
197
+ st.success(f"πŸŽ‰ Loaded {FILE_TYPES.get(file_type, 'πŸ“„')} file: {uploaded_file.name}")
198
+
199
+ # Process multiple file upload
200
+ if uploaded_files:
201
+ for uploaded_file in uploaded_files:
202
+ content, file_type = read_file_content(uploaded_file)
203
+ if content is not None:
204
+ st.session_state.file_data[uploaded_file.name] = content
205
+ st.session_state.file_types[uploaded_file.name] = file_type
206
+ st.success(f"πŸŽ‰ Loaded {len(uploaded_files)} files")
207
+
208
+ # Show file history
209
+ show_file_history()
210
+
211
+ # Show individual files
212
+ if st.session_state.file_data:
213
+ st.subheader("πŸ“‚ Your Files")
214
+ for filename, content in st.session_state.file_data.items():
215
+ file_type = st.session_state.file_types[filename]
216
+ with st.expander(f"{FILE_TYPES.get(file_type, 'πŸ“„')} {filename}"):
217
+ if file_type == "md":
218
+ content = create_markdown_tabs(content, filename)
219
+ else:
220
+ edited_content = st.text_area(
221
+ "Content",
222
+ content,
223
+ height=300,
224
+ key=f"edit_{filename}"
225
+ )
226
+ if edited_content != content:
227
+ st.session_state.file_data[filename] = edited_content
228
+ content = edited_content
229
+
230
+ if st.button(f"πŸ’Ύ Save {filename}"):
231
+ if save_file_content(content, filename, file_type):
232
+ st.success(f"✨ Saved {filename} successfully!")
233
+
234
+ with book_tab:
235
+ show_book_view()
236
+
237
+ if __name__ == "__main__":
238
+ main()