Spaces:
Running
Running
File size: 23,745 Bytes
51c1918 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
import streamlit as st
from streamlit.components.v1 import html
from pathlib import Path
import json
import time
from datetime import datetime
import re
import pandas as pd
import yaml
from io import StringIO
import openpyxl
import csv
import base64
import glob
import os
# Add this function after the imports and before other functions
def scan_and_load_files():
"""π File Detective - Scans directory for supported files and loads them automatically"""
loaded_files = []
# Get all files with supported extensions
for ext in FILE_TYPES.keys():
files = glob.glob(f"*.{ext}")
for filepath in files:
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
file_type = filepath.split('.')[-1].lower()
# Store file content and type
st.session_state.file_data[filepath] = content
st.session_state.file_types[filepath] = file_type
# Special handling for markdown files
if file_type == 'md':
st.session_state.md_outline[filepath] = parse_markdown_outline(content)
st.session_state.rendered_content[filepath] = content
# Add to markdown files history if not already present
if filepath not in [f["filename"] for f in st.session_state.md_files_history]:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
encoded_content = encode_content(content)
st.session_state.md_files_history.append({
"filename": filepath,
"timestamp": timestamp,
"content": encoded_content
})
# Create initial version history
if filepath not in st.session_state.md_versions:
st.session_state.md_versions[filepath] = []
st.session_state.md_versions[filepath].append({
"timestamp": timestamp,
"content": encoded_content,
"action": "auto-loaded"
})
loaded_files.append(filepath)
except Exception as e:
st.error(f"π¨ Error loading {filepath}: {str(e)}")
# Update combined markdown after loading all files
if loaded_files:
st.session_state.combined_markdown = combine_markdown_files()
return loaded_files
# Modify the main function to include initial file scanning
def main():
# Add a reset button in sidebar
if st.sidebar.button("π Reset & Rescan Files"):
# Clear all session state
for key in list(st.session_state.keys()):
del st.session_state[key]
st.experimental_rerun()
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
# Initialize session state
if 'file_data' not in st.session_state:
st.session_state.file_data = {}
if 'file_types' not in st.session_state:
st.session_state.file_types = {}
if 'md_outline' not in st.session_state:
st.session_state.md_outline = {}
if 'rendered_content' not in st.session_state:
st.session_state.rendered_content = {}
if 'file_history' not in st.session_state:
st.session_state.file_history = []
if 'md_versions' not in st.session_state:
st.session_state.md_versions = {}
if 'md_files_history' not in st.session_state:
st.session_state.md_files_history = []
if 'combined_markdown' not in st.session_state:
st.session_state.combined_markdown = ""
# Scan for existing files on startup
if 'files_scanned' not in st.session_state:
loaded_files = scan_and_load_files()
if loaded_files:
st.success(f"π Auto-loaded {len(loaded_files)} existing files: {', '.join(loaded_files)}")
st.session_state.files_scanned = True
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
# Scan for existing files on startup
if 'files_scanned' not in st.session_state:
loaded_files = scan_and_load_files()
if loaded_files:
st.success(f"π Auto-loaded {len(loaded_files)} existing files: {', '.join(loaded_files)}")
st.session_state.files_scanned = True
# Show markdown history in sidebar
show_sidebar_history()
# Add tabs for different upload methods
upload_tab, book_tab = st.tabs(["π€ File Upload", "π Book View"])
with upload_tab:
# Add a rescan button
if st.button("π Rescan Directory"):
st.session_state.files_scanned = False
st.experimental_rerun()
col1, col2 = st.columns(2)
with col1:
single_uploaded_file = st.file_uploader(
"π€ Upload single file",
type=list(FILE_TYPES.keys()),
help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()]),
key="single_uploader"
)
with col2:
multiple_uploaded_files = st.file_uploader(
"π Upload multiple files",
type=list(FILE_TYPES.keys()),
accept_multiple_files=True,
help="Upload multiple files to view as a book",
key="multiple_uploader"
)
# Process single file upload
if single_uploaded_file:
content, file_type = read_file_content(single_uploaded_file)
if content is not None:
st.session_state.file_data[single_uploaded_file.name] = content
st.session_state.file_types[single_uploaded_file.name] = file_type
st.success(f"π Loaded {FILE_TYPES.get(file_type, 'π')} file: {single_uploaded_file.name}")
# Process multiple file upload
if multiple_uploaded_files:
for uploaded_file in multiple_uploaded_files:
content, file_type = read_file_content(uploaded_file)
if content is not None:
st.session_state.file_data[uploaded_file.name] = content
st.session_state.file_types[uploaded_file.name] = file_type
st.success(f"π Loaded {len(multiple_uploaded_files)} files")
# Show file history
show_file_history()
# Show individual files
if st.session_state.file_data:
st.subheader("π Your Files")
for filename, content in st.session_state.file_data.items():
file_type = st.session_state.file_types[filename]
with st.expander(f"{FILE_TYPES.get(file_type, 'π')} {filename}"):
if file_type == "md":
content = create_markdown_tabs(content, filename)
else:
edited_content = st.text_area(
"Content",
content,
height=300,
key=f"edit_{filename}"
)
if edited_content != content:
st.session_state.file_data[filename] = edited_content
content = edited_content
if st.button(f"πΎ Save {filename}"):
if save_file_content(content, filename, file_type):
st.success(f"β¨ Saved {filename} successfully!")
with book_tab:
show_book_view()
# π¨ File type emojis - Making file types fun and visual!
FILE_TYPES = {
"md": "π Markdown",
"txt": "π Text",
"json": "π§ JSON",
"csv": "π CSV",
"xlsx": "π Excel",
"yaml": "βοΈ YAML",
"xml": "π XML"
}
# π§ Brain initialization - Setting up our app's memory!
if 'file_data' not in st.session_state:
st.session_state.file_data = {}
if 'file_types' not in st.session_state:
st.session_state.file_types = {}
if 'md_outline' not in st.session_state:
st.session_state.md_outline = {}
if 'rendered_content' not in st.session_state:
st.session_state.rendered_content = {}
if 'file_history' not in st.session_state:
st.session_state.file_history = []
if 'md_versions' not in st.session_state:
st.session_state.md_versions = {}
if 'md_files_history' not in st.session_state:
st.session_state.md_files_history = []
if 'combined_markdown' not in st.session_state:
st.session_state.combined_markdown = ""
# π§Ή Clean Sweep! - Decluttering our markdown files
def delete_all_md_files():
"""Delete all markdown files except README.md"""
files_to_remove = [
f for f in st.session_state.md_files_history
if f["filename"] != "README.md"
]
for file in files_to_remove:
filename = file["filename"]
if filename in st.session_state.file_data:
del st.session_state.file_data[filename]
if filename in st.session_state.file_types:
del st.session_state.file_types[filename]
if filename in st.session_state.md_outline:
del st.session_state.md_outline[filename]
if filename in st.session_state.rendered_content:
del st.session_state.rendered_content[filename]
if filename in st.session_state.md_versions:
del st.session_state.md_versions[filename]
st.session_state.md_files_history = [
f for f in st.session_state.md_files_history
if f["filename"] == "README.md"
]
st.session_state.combined_markdown = ""
return len(files_to_remove)
# π Download Gift Wrapper - Making files downloadable with style!
def get_binary_file_downloader_html(bin_file, file_label='File'):
"""Generate a link allowing the data in a given file to be downloaded"""
b64 = base64.b64encode(bin_file.encode()).decode()
return f'<a href="data:text/plain;base64,{b64}" download="{file_label}">π₯ Download {file_label}</a>'
# π Secret Keeper - Encoding our content safely
def encode_content(content):
"""Encode content to base64"""
return base64.b64encode(content.encode()).decode()
# π Mystery Solver - Decoding our secret content
def decode_content(encoded_content):
"""Decode content from base64"""
return base64.b64decode(encoded_content.encode()).decode()
# π Book Maker - Combining markdown files into a beautiful book
def combine_markdown_files():
"""Combine all markdown files into a single document"""
combined = []
for md_file in sorted(st.session_state.md_files_history, key=lambda x: x["filename"]):
content = decode_content(md_file["content"])
combined.append(f"# {md_file['filename']}\n\n{content}\n\n---\n\n")
return "".join(combined)
# π History Scribe - Recording every file action with precision
def add_to_history(filename, content, action="uploaded"):
"""Add a file action to the history with timestamp"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
encoded_content = encode_content(content)
history_entry = {
"timestamp": timestamp,
"filename": filename,
"action": action,
"content": encoded_content
}
st.session_state.file_history.insert(0, history_entry)
if filename.endswith('.md'):
if filename not in st.session_state.md_versions:
st.session_state.md_versions[filename] = []
st.session_state.md_versions[filename].append({
"timestamp": timestamp,
"content": encoded_content,
"action": action
})
if filename not in [f["filename"] for f in st.session_state.md_files_history]:
st.session_state.md_files_history.append({
"filename": filename,
"timestamp": timestamp,
"content": encoded_content
})
st.session_state.combined_markdown = combine_markdown_files()
# π Shelf Display - Showing our markdown collection in the sidebar
def show_sidebar_history():
"""Display markdown file history in the sidebar"""
st.sidebar.markdown("### π Markdown Files History")
if st.sidebar.button("π§Ή Delete All (except README.md)"):
deleted_count = delete_all_md_files()
st.sidebar.success(f"Deleted {deleted_count} markdown files")
st.rerun()
for md_file in st.session_state.md_files_history:
col1, col2, col3 = st.sidebar.columns([2, 1, 1])
with col1:
st.markdown(f"**{md_file['filename']}**")
with col2:
if st.button("π Open", key=f"open_{md_file['filename']}"):
content = decode_content(md_file['content'])
st.session_state.file_data[md_file['filename']] = content
st.session_state.file_types[md_file['filename']] = "md"
st.session_state.md_outline[md_file['filename']] = parse_markdown_outline(content)
st.rerun()
with col3:
download_link = get_binary_file_downloader_html(
decode_content(md_file['content']),
md_file['filename']
)
st.markdown(download_link, unsafe_allow_html=True)
# π Book Display - Showing our combined markdown masterpiece
def show_book_view():
"""Display all markdown files in a book-like format"""
if st.session_state.combined_markdown:
st.markdown("## π Book View")
st.markdown(st.session_state.combined_markdown)
# π Time Traveler - Showing our file's journey through time
def show_file_history():
"""Display the file history in a collapsible section"""
if st.session_state.file_history:
with st.expander("π File History", expanded=False):
st.markdown("### Recent File Activities")
for entry in st.session_state.file_history:
col1, col2 = st.columns([2, 3])
with col1:
st.markdown(f"**{entry['timestamp']}**")
with col2:
st.markdown(f"{entry['action'].title()}: {entry['filename']}")
# β° Time Machine - Exploring previous versions of our files
def show_markdown_versions(filename):
"""Display previous versions of a markdown file"""
if filename in st.session_state.md_versions:
versions = st.session_state.md_versions[filename]
if len(versions) > 1:
st.markdown("### π Previous Versions")
version_idx = st.selectbox(
"Select version to view",
range(len(versions)-1),
format_func=lambda x: f"Version {len(versions)-1-x} - {versions[x]['timestamp']}"
)
if version_idx is not None:
version = versions[version_idx]
decoded_content = decode_content(version['content'])
st.text_area(
"Content",
decoded_content,
height=200,
key=f"version_{filename}_{version_idx}",
disabled=True
)
if st.button(f"Restore to this version", key=f"restore_{filename}_{version_idx}"):
st.session_state.file_data[filename] = decoded_content
st.session_state.md_outline[filename] = parse_markdown_outline(decoded_content)
add_to_history(filename, decoded_content, "restored")
st.rerun()
# πΊοΈ Map Maker - Creating a beautiful outline of our markdown
def parse_markdown_outline(content):
"""Generate an outline from markdown content"""
lines = content.split('\n')
outline = []
for line in lines:
if line.strip().startswith('#'):
level = len(line.split()[0])
title = line.strip('#').strip()
outline.append({
'level': level,
'title': title,
'indent': ' ' * (level - 1)
})
return outline
# π Tab Master - Creating beautiful tabs for our markdown content
def create_markdown_tabs(content, filename):
"""Create tabs for markdown content viewing and editing"""
tab1, tab2, tab3 = st.tabs(["π Editor", "π Preview", "π History"])
with tab1:
edited_content = st.text_area(
"Edit your markdown",
content,
height=300,
key=f"edit_{filename}"
)
if edited_content != content:
st.session_state.file_data[filename] = edited_content
st.session_state.md_outline[filename] = parse_markdown_outline(edited_content)
add_to_history(filename, edited_content, "edited")
content = edited_content
with tab2:
st.markdown("### Preview")
st.markdown(content)
if filename in st.session_state.md_outline:
st.markdown("---")
st.markdown("### π Document Outline")
for item in st.session_state.md_outline[filename]:
st.markdown(f"{item['indent']}β’ {item['title']}")
with tab3:
show_markdown_versions(filename)
return content
# π€ File Reader - Smart file reading with a smile!
def read_file_content(uploaded_file):
"""Smart file reader with enhanced markdown handling"""
file_type = uploaded_file.name.split('.')[-1].lower()
try:
if file_type == 'md':
content = uploaded_file.getvalue().decode()
st.session_state.md_outline[uploaded_file.name] = parse_markdown_outline(content)
st.session_state.rendered_content[uploaded_file.name] = content
add_to_history(uploaded_file.name, content)
return content, "md"
elif file_type == 'csv':
df = pd.read_csv(uploaded_file)
return df.to_string(), "csv"
elif file_type == 'xlsx':
df = pd.read_excel(uploaded_file)
return df.to_string(), "xlsx"
elif file_type == 'json':
content = json.load(uploaded_file)
return json.dumps(content, indent=2), "json"
elif file_type == 'yaml':
content = yaml.safe_load(uploaded_file)
return yaml.dump(content), "yaml"
else: # Default text handling
return uploaded_file.getvalue().decode(), "txt"
except Exception as e:
st.error(f"π¨ Oops! Error reading {uploaded_file.name}: {str(e)}")
return None, None
# πΎ File Saver - Keeping our files safe and sound
def save_file_content(content, filename, file_type):
"""Smart file saver with enhanced markdown handling"""
try:
if file_type == "md":
with open(filename, 'w') as f:
f.write(content)
st.session_state.rendered_content[filename] = content
add_to_history(filename, content, "saved")
elif file_type in ["csv", "xlsx"]:
df = pd.read_csv(StringIO(content)) if file_type == "csv" else pd.read_excel(StringIO(content))
if file_type == "csv":
df.to_csv(filename, index=False)
else:
df.to_excel(filename, index=False)
elif file_type == "json":
with open(filename, 'w') as f:
json.dump(json.loads(content), f, indent=2)
elif file_type == "yaml":
with open(filename, 'w') as f:
yaml.dump(yaml.safe_load(content), f)
else: # Default text handling
with open(filename, 'w') as f:
f.write(content)
return True
except Exception as e:
st.error(f"π¨ Error saving {filename}: {str(e)}")
return False
# π Main Show - Where the magic happens!
def main():
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
# Show markdown history in sidebar
show_sidebar_history()
# Add tabs for different upload methods
upload_tab, book_tab = st.tabs(["π€ File Upload", "π Book View"])
with upload_tab:
col1, col2 = st.columns(2)
with col1:
single_uploaded_file = st.file_uploader(
"π€ Upload single file",
type=list(FILE_TYPES.keys()),
help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()]),
key="single_uploader"
)
with col2:
multiple_uploaded_files = st.file_uploader(
"π Upload multiple files",
type=list(FILE_TYPES.keys()),
accept_multiple_files=True,
help="Upload multiple files to view as a book",
key="multiple_uploader"
)
# Process single file upload
if single_uploaded_file:
content, file_type = read_file_content(single_uploaded_file)
if content is not None:
st.session_state.file_data[single_uploaded_file.name] = content
st.session_state.file_types[single_uploaded_file.name] = file_type
st.success(f"π Loaded {FILE_TYPES.get(file_type, 'π')} file: {single_uploaded_file.name}")
# Process multiple file upload
if multiple_uploaded_files:
for uploaded_file in multiple_uploaded_files:
content, file_type = read_file_content(uploaded_file)
if content is not None:
st.session_state.file_data[uploaded_file.name] = content
st.session_state.file_types[uploaded_file.name] = file_type
st.success(f"π Loaded {len(multiple_uploaded_files)} files")
# Show file history
show_file_history()
# Show individual files
if st.session_state.file_data:
st.subheader("π Your Files")
for filename, content in st.session_state.file_data.items():
file_type = st.session_state.file_types[filename]
with st.expander(f"{FILE_TYPES.get(file_type, 'π')} {filename}"):
if file_type == "md":
content = create_markdown_tabs(content, filename)
else:
edited_content = st.text_area(
"Content",
content,
height=300,
key=f"edit_{filename}"
)
if edited_content != content:
st.session_state.file_data[filename] = edited_content
content = edited_content
if st.button(f"πΎ Save {filename}"):
if save_file_content(content, filename, file_type):
st.success(f"β¨ Saved {filename} successfully!")
with book_tab:
show_book_view()
if __name__ == "__main__":
main() |