awacke1's picture
Update app.py
6f51e0d verified
raw
history blame
6.27 kB
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 markdown
import yaml
from io import StringIO
import openpyxl
import csv
# πŸ¦„βœ¨ Enhanced state initialization with file type tracking!
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 = {} # πŸ“ Track file types for special handling
if 'md_outline' not in st.session_state:
st.session_state.md_outline = {} # πŸ“‘ Store markdown outlines
# 🎯 Supported file types and their handlers
FILE_TYPES = {
"md": "πŸ“ Markdown",
"txt": "πŸ“„ Text",
"json": "πŸ”§ JSON",
"csv": "πŸ“Š CSV",
"xlsx": "πŸ“— Excel",
"yaml": "βš™οΈ YAML",
"xml": "πŸ”— XML"
}
def parse_markdown_outline(content):
"""πŸ“‘ Generate a cute outline from markdown!"""
lines = content.split('\n')
outline = []
for line in lines:
if line.strip().startswith('#'):
level = len(line.split()[0]) # Count #'s
title = line.strip('#').strip()
outline.append({
'level': level,
'title': title,
'indent': ' ' * (level - 1)
})
return outline
def read_file_content(uploaded_file):
"""πŸ“š Smart file reader with type detection!"""
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)
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
def save_file_content(content, filename, file_type):
"""πŸ’Ύ Smart file saver with type handling!"""
try:
if file_type == "md":
with open(filename, 'w') as f:
f.write(content)
elif file_type in ["csv", "xlsx"]:
# Convert string back to DataFrame
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
def show_markdown_preview(content):
"""πŸ‘€ Show pretty markdown preview!"""
st.markdown("### πŸ‘€ Markdown Preview")
st.markdown(content)
def show_markdown_outline(filename):
"""πŸ“‘ Display pretty markdown outline!"""
if filename in st.session_state.md_outline:
st.markdown("### πŸ“‘ Document Outline")
for item in st.session_state.md_outline[filename]:
st.markdown(f"{item['indent']}β€’ {item['title']}")
def main():
st.title("πŸ“šβœ¨ Super Smart File Handler with Markdown Magic! βœ¨πŸ“š")
# πŸ“ Enhanced file upload with type support
uploaded_file = st.file_uploader(
"πŸ“€ Upload your file!",
type=list(FILE_TYPES.keys()),
help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()])
)
if uploaded_file:
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 {FILE_TYPES.get(file_type, 'πŸ“„')} file: {uploaded_file.name}")
# πŸ“ Special handling for markdown files
if file_type == "md":
show_markdown_preview(content)
show_markdown_outline(uploaded_file.name)
# πŸ“‚ File Display and Editing
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}"):
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
if file_type == "md":
st.session_state.md_outline[filename] = parse_markdown_outline(edited_content)
show_markdown_preview(edited_content)
show_markdown_outline(filename)
if st.button(f"πŸ’Ύ Save {filename}"):
if save_file_content(edited_content, filename, file_type):
st.success(f"✨ Saved {filename} successfully!")
if __name__ == "__main__":
main()