Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -12,7 +12,7 @@ import openpyxl
|
|
12 |
import csv
|
13 |
import base64
|
14 |
|
15 |
-
#
|
16 |
FILE_TYPES = {
|
17 |
"md": "π Markdown",
|
18 |
"txt": "π Text",
|
@@ -23,7 +23,7 @@ FILE_TYPES = {
|
|
23 |
"xml": "π XML"
|
24 |
}
|
25 |
|
26 |
-
#
|
27 |
if 'file_data' not in st.session_state:
|
28 |
st.session_state.file_data = {}
|
29 |
if 'file_types' not in st.session_state:
|
@@ -41,6 +41,7 @@ if 'md_files_history' not in st.session_state:
|
|
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 = [
|
@@ -67,19 +68,23 @@ def delete_all_md_files():
|
|
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 = []
|
@@ -88,6 +93,7 @@ def combine_markdown_files():
|
|
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")
|
@@ -100,7 +106,6 @@ def add_to_history(filename, content, action="uploaded"):
|
|
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] = []
|
@@ -110,7 +115,6 @@ def add_to_history(filename, content, action="uploaded"):
|
|
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,
|
@@ -118,15 +122,14 @@ def add_to_history(filename, content, action="uploaded"):
|
|
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 |
-
|
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()
|
@@ -152,22 +155,180 @@ def show_sidebar_history():
|
|
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 |
-
#
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
|
@@ -188,15 +349,16 @@ def main():
|
|
188 |
help="Upload multiple files to view as a book"
|
189 |
)
|
190 |
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
|
|
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)
|
@@ -205,10 +367,10 @@ def main():
|
|
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():
|
@@ -231,8 +393,10 @@ def main():
|
|
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()
|
|
|
12 |
import csv
|
13 |
import base64
|
14 |
|
15 |
+
# π¨ File type emojis - Making file types fun and visual!
|
16 |
FILE_TYPES = {
|
17 |
"md": "π Markdown",
|
18 |
"txt": "π Text",
|
|
|
23 |
"xml": "π XML"
|
24 |
}
|
25 |
|
26 |
+
# π§ Brain initialization - Setting up our app's memory!
|
27 |
if 'file_data' not in st.session_state:
|
28 |
st.session_state.file_data = {}
|
29 |
if 'file_types' not in st.session_state:
|
|
|
41 |
if 'combined_markdown' not in st.session_state:
|
42 |
st.session_state.combined_markdown = ""
|
43 |
|
44 |
+
# π§Ή Clean Sweep! - Decluttering our markdown files
|
45 |
def delete_all_md_files():
|
46 |
"""Delete all markdown files except README.md"""
|
47 |
files_to_remove = [
|
|
|
68 |
st.session_state.combined_markdown = ""
|
69 |
return len(files_to_remove)
|
70 |
|
71 |
+
# π Download Gift Wrapper - Making files downloadable with style!
|
72 |
def get_binary_file_downloader_html(bin_file, file_label='File'):
|
73 |
"""Generate a link allowing the data in a given file to be downloaded"""
|
74 |
b64 = base64.b64encode(bin_file.encode()).decode()
|
75 |
return f'<a href="data:text/plain;base64,{b64}" download="{file_label}">π₯ Download {file_label}</a>'
|
76 |
|
77 |
+
# π Secret Keeper - Encoding our content safely
|
78 |
def encode_content(content):
|
79 |
"""Encode content to base64"""
|
80 |
return base64.b64encode(content.encode()).decode()
|
81 |
|
82 |
+
# π Mystery Solver - Decoding our secret content
|
83 |
def decode_content(encoded_content):
|
84 |
"""Decode content from base64"""
|
85 |
return base64.b64decode(encoded_content.encode()).decode()
|
86 |
|
87 |
+
# π Book Maker - Combining markdown files into a beautiful book
|
88 |
def combine_markdown_files():
|
89 |
"""Combine all markdown files into a single document"""
|
90 |
combined = []
|
|
|
93 |
combined.append(f"# {md_file['filename']}\n\n{content}\n\n---\n\n")
|
94 |
return "".join(combined)
|
95 |
|
96 |
+
# π History Scribe - Recording every file action with precision
|
97 |
def add_to_history(filename, content, action="uploaded"):
|
98 |
"""Add a file action to the history with timestamp"""
|
99 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
106 |
}
|
107 |
st.session_state.file_history.insert(0, history_entry)
|
108 |
|
|
|
109 |
if filename.endswith('.md'):
|
110 |
if filename not in st.session_state.md_versions:
|
111 |
st.session_state.md_versions[filename] = []
|
|
|
115 |
"action": action
|
116 |
})
|
117 |
|
|
|
118 |
if filename not in [f["filename"] for f in st.session_state.md_files_history]:
|
119 |
st.session_state.md_files_history.append({
|
120 |
"filename": filename,
|
|
|
122 |
"content": encoded_content
|
123 |
})
|
124 |
|
|
|
125 |
st.session_state.combined_markdown = combine_markdown_files()
|
126 |
|
127 |
+
# π Shelf Display - Showing our markdown collection in the sidebar
|
128 |
def show_sidebar_history():
|
129 |
"""Display markdown file history in the sidebar"""
|
130 |
st.sidebar.markdown("### π Markdown Files History")
|
131 |
|
132 |
+
if st.sidebar.button("π§Ή Delete All (except README.md)"):
|
|
|
133 |
deleted_count = delete_all_md_files()
|
134 |
st.sidebar.success(f"Deleted {deleted_count} markdown files")
|
135 |
st.experimental_rerun()
|
|
|
155 |
)
|
156 |
st.markdown(download_link, unsafe_allow_html=True)
|
157 |
|
158 |
+
# π Book Display - Showing our combined markdown masterpiece
|
159 |
def show_book_view():
|
160 |
"""Display all markdown files in a book-like format"""
|
161 |
if st.session_state.combined_markdown:
|
162 |
st.markdown("## π Book View")
|
163 |
st.markdown(st.session_state.combined_markdown)
|
164 |
|
165 |
+
# π Time Traveler - Showing our file's journey through time
|
166 |
+
def show_file_history():
|
167 |
+
"""Display the file history in a collapsible section"""
|
168 |
+
if st.session_state.file_history:
|
169 |
+
with st.expander("π File History", expanded=False):
|
170 |
+
st.markdown("### Recent File Activities")
|
171 |
+
for entry in st.session_state.file_history:
|
172 |
+
col1, col2 = st.columns([2, 3])
|
173 |
+
with col1:
|
174 |
+
st.markdown(f"**{entry['timestamp']}**")
|
175 |
+
with col2:
|
176 |
+
st.markdown(f"{entry['action'].title()}: {entry['filename']}")
|
177 |
|
178 |
+
# β° Time Machine - Exploring previous versions of our files
|
179 |
+
def show_markdown_versions(filename):
|
180 |
+
"""Display previous versions of a markdown file"""
|
181 |
+
if filename in st.session_state.md_versions:
|
182 |
+
versions = st.session_state.md_versions[filename]
|
183 |
+
if len(versions) > 1:
|
184 |
+
st.markdown("### π Previous Versions")
|
185 |
+
version_idx = st.selectbox(
|
186 |
+
"Select version to view",
|
187 |
+
range(len(versions)-1),
|
188 |
+
format_func=lambda x: f"Version {len(versions)-1-x} - {versions[x]['timestamp']}"
|
189 |
+
)
|
190 |
+
|
191 |
+
if version_idx is not None:
|
192 |
+
version = versions[version_idx]
|
193 |
+
decoded_content = decode_content(version['content'])
|
194 |
+
st.text_area(
|
195 |
+
"Content",
|
196 |
+
decoded_content,
|
197 |
+
height=200,
|
198 |
+
key=f"version_{filename}_{version_idx}",
|
199 |
+
disabled=True
|
200 |
+
)
|
201 |
+
if st.button(f"Restore to this version", key=f"restore_{filename}_{version_idx}"):
|
202 |
+
st.session_state.file_data[filename] = decoded_content
|
203 |
+
st.session_state.md_outline[filename] = parse_markdown_outline(decoded_content)
|
204 |
+
add_to_history(filename, decoded_content, "restored")
|
205 |
+
st.experimental_rerun()
|
206 |
+
|
207 |
+
# πΊοΈ Map Maker - Creating a beautiful outline of our markdown
|
208 |
+
def parse_markdown_outline(content):
|
209 |
+
"""Generate an outline from markdown content"""
|
210 |
+
lines = content.split('\n')
|
211 |
+
outline = []
|
212 |
+
for line in lines:
|
213 |
+
if line.strip().startswith('#'):
|
214 |
+
level = len(line.split()[0])
|
215 |
+
title = line.strip('#').strip()
|
216 |
+
outline.append({
|
217 |
+
'level': level,
|
218 |
+
'title': title,
|
219 |
+
'indent': ' ' * (level - 1)
|
220 |
+
})
|
221 |
+
return outline
|
222 |
+
|
223 |
+
# π Tab Master - Creating beautiful tabs for our markdown content
|
224 |
+
def create_markdown_tabs(content, filename):
|
225 |
+
"""Create tabs for markdown content viewing and editing"""
|
226 |
+
tab1, tab2, tab3 = st.tabs(["π Editor", "π Preview", "π History"])
|
227 |
+
|
228 |
+
with tab1:
|
229 |
+
edited_content = st.text_area(
|
230 |
+
"Edit your markdown",
|
231 |
+
content,
|
232 |
+
height=300,
|
233 |
+
key=f"edit_{filename}"
|
234 |
+
)
|
235 |
+
|
236 |
+
if edited_content != content:
|
237 |
+
st.session_state.file_data[filename] = edited_content
|
238 |
+
st.session_state.md_outline[filename] = parse_markdown_outline(edited_content)
|
239 |
+
add_to_history(filename, edited_content, "edited")
|
240 |
+
content = edited_content
|
241 |
+
|
242 |
+
with tab2:
|
243 |
+
st.markdown("### Preview")
|
244 |
+
st.markdown(content)
|
245 |
+
|
246 |
+
if filename in st.session_state.md_outline:
|
247 |
+
st.markdown("---")
|
248 |
+
st.markdown("### π Document Outline")
|
249 |
+
for item in st.session_state.md_outline[filename]:
|
250 |
+
st.markdown(f"{item['indent']}β’ {item['title']}")
|
251 |
+
|
252 |
+
with tab3:
|
253 |
+
show_markdown_versions(filename)
|
254 |
+
|
255 |
+
return content
|
256 |
+
|
257 |
+
# π€ File Reader - Smart file reading with a smile!
|
258 |
+
def read_file_content(uploaded_file):
|
259 |
+
"""Smart file reader with enhanced markdown handling"""
|
260 |
+
file_type = uploaded_file.name.split('.')[-1].lower()
|
261 |
+
try:
|
262 |
+
if file_type == 'md':
|
263 |
+
content = uploaded_file.getvalue().decode()
|
264 |
+
st.session_state.md_outline[uploaded_file.name] = parse_markdown_outline(content)
|
265 |
+
st.session_state.rendered_content[uploaded_file.name] = content
|
266 |
+
add_to_history(uploaded_file.name, content)
|
267 |
+
return content, "md"
|
268 |
+
|
269 |
+
elif file_type == 'csv':
|
270 |
+
df = pd.read_csv(uploaded_file)
|
271 |
+
return df.to_string(), "csv"
|
272 |
+
|
273 |
+
elif file_type == 'xlsx':
|
274 |
+
df = pd.read_excel(uploaded_file)
|
275 |
+
return df.to_string(), "xlsx"
|
276 |
+
|
277 |
+
elif file_type == 'json':
|
278 |
+
content = json.load(uploaded_file)
|
279 |
+
return json.dumps(content, indent=2), "json"
|
280 |
+
|
281 |
+
elif file_type == 'yaml':
|
282 |
+
content = yaml.safe_load(uploaded_file)
|
283 |
+
return yaml.dump(content), "yaml"
|
284 |
+
|
285 |
+
else: # Default text handling
|
286 |
+
return uploaded_file.getvalue().decode(), "txt"
|
287 |
+
|
288 |
+
except Exception as e:
|
289 |
+
st.error(f"π¨ Oops! Error reading {uploaded_file.name}: {str(e)}")
|
290 |
+
return None, None
|
291 |
+
|
292 |
+
# πΎ File Saver - Keeping our files safe and sound
|
293 |
+
def save_file_content(content, filename, file_type):
|
294 |
+
"""Smart file saver with enhanced markdown handling"""
|
295 |
+
try:
|
296 |
+
if file_type == "md":
|
297 |
+
with open(filename, 'w') as f:
|
298 |
+
f.write(content)
|
299 |
+
st.session_state.rendered_content[filename] = content
|
300 |
+
add_to_history(filename, content, "saved")
|
301 |
+
|
302 |
+
elif file_type in ["csv", "xlsx"]:
|
303 |
+
df = pd.read_csv(StringIO(content)) if file_type == "csv" else pd.read_excel(StringIO(content))
|
304 |
+
if file_type == "csv":
|
305 |
+
df.to_csv(filename, index=False)
|
306 |
+
else:
|
307 |
+
df.to_excel(filename, index=False)
|
308 |
+
|
309 |
+
elif file_type == "json":
|
310 |
+
with open(filename, 'w') as f:
|
311 |
+
json.dump(json.loads(content), f, indent=2)
|
312 |
+
|
313 |
+
elif file_type == "yaml":
|
314 |
+
with open(filename, 'w') as f:
|
315 |
+
yaml.dump(yaml.safe_load(content), f)
|
316 |
+
|
317 |
+
else: # Default text handling
|
318 |
+
with open(filename, 'w') as f:
|
319 |
+
f.write(content)
|
320 |
+
|
321 |
+
return True
|
322 |
+
except Exception as e:
|
323 |
+
st.error(f"π¨ Error saving {filename}: {str(e)}")
|
324 |
+
return False
|
325 |
+
|
326 |
+
# π Main Show - Where the magic happens!
|
327 |
def main():
|
328 |
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
|
329 |
|
|
|
330 |
show_sidebar_history()
|
331 |
|
|
|
332 |
upload_tab, book_tab = st.tabs(["π€ File Upload", "π Book View"])
|
333 |
|
334 |
with upload_tab:
|
|
|
349 |
help="Upload multiple files to view as a book"
|
350 |
)
|
351 |
|
352 |
+
# Process single file upload
|
353 |
+
if uploaded_file:
|
354 |
+
content, file_type = read_file_content(uploaded_file)
|
355 |
+
if content is not None:
|
356 |
+
st.session_state.file_data[uploaded_file.name] = content
|
357 |
+
st.session_state.file_types[uploaded_file.name] = file_type # This is the correct line
|
358 |
+
st.success(f"π Loaded {FILE_TYPES.get(file_type, 'π')} file: {uploaded_file.name}")
|
359 |
+
|
360 |
|
361 |
+
# π Process multiple file upload - Bulk file loading magic!
|
362 |
if uploaded_files:
|
363 |
for uploaded_file in uploaded_files:
|
364 |
content, file_type = read_file_content(uploaded_file)
|
|
|
367 |
st.session_state.file_types[uploaded_file.name] = file_type
|
368 |
st.success(f"π Loaded {len(uploaded_files)} files")
|
369 |
|
370 |
+
# π Show the journey - Display file history
|
371 |
show_file_history()
|
372 |
|
373 |
+
# π File Explorer - Show and manage individual files
|
374 |
if st.session_state.file_data:
|
375 |
st.subheader("π Your Files")
|
376 |
for filename, content in st.session_state.file_data.items():
|
|
|
393 |
if save_file_content(content, filename, file_type):
|
394 |
st.success(f"β¨ Saved {filename} successfully!")
|
395 |
|
396 |
+
# π Book Mode - Show all markdown files in book format
|
397 |
with book_tab:
|
398 |
show_book_view()
|
399 |
|
400 |
+
# π Launch the app!
|
401 |
if __name__ == "__main__":
|
402 |
main()
|